您的位置:首页 > 其它

设计模式-装饰模式

2015-09-30 09:20 120 查看
装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。


装饰模式的结构

装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。

  装饰模式的类图如下:



  在装饰模式中的角色有:

  ●  抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。

  ●  具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。

  ●  装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

  ●  具体装饰([b]ConcreteDecorator)角色:[/b]负责给构件对象“贴上”附加的责任。


实例代码:

1.定义需要装饰的对象
public class Person {
private String name;

public Person(){};
public Person(String name) {
this.name = name;
}
public void show(){
System.out.println("装扮的" + name);
}
}


2.定义装饰品基类
public class Finery extends Person {

protected Person component;

// 打扮
public void decorate(Person component) {
this.component = component;
}

@Override
public void show() {
if (component != null) {
component.show();
}
}
}
3.列举具体装饰品

public class BigTrouser extends Finery {

@Override
public void show() {
System.out.println("短裤");
super.show();
}
}
public class Sneaker extends Finery{

@Override
public void show() {
System.out.println("运动鞋");
super.show();
}
}
public class TShirts extends Finery{

@Override
public void show() {
System.out.println("T恤");
super.show();
}

}

4.测试类

public class Test {
public static void main(String[] args) {
Person person = new Person("张三");
System.out.println("开始装扮");
TShirts ts = new TShirts();
BigTrouser bt = new BigTrouser();
Sneaker sk = new Sneaker();
ts.decorate(person);
bt.decorate(ts);
sk.decorate(bt);
sk.show();
}
}


5.

输出:
开始装扮

运动鞋

短裤

T恤

装扮的张三


齐天大圣的例子

  孙悟空有七十二般变化,他的每一种变化都给他带来一种附加的本领。他变成鱼儿时,就可以到水里游泳;他变成鸟儿时,就可以在天上飞行。

  本例中,Component的角色便由鼎鼎大名的齐天大圣扮演;ConcreteComponent的角色属于大圣的本尊,就是猢狲本人;Decorator的角色由大圣的七十二变扮演。而ConcreteDecorator的角色便是鱼儿、鸟儿等七十二般变化。




源代码

抽象构件角色“齐天大圣”接口定义了一个move()方法,这是所有的具体构件类和装饰类必须实现的。

//大圣的尊号
public interface TheGreatestSage {
public void move();
}


具体构件角色“大圣本尊”猢狲类

public class Monkey implements TheGreatestSage {
@Override
public void move() {
//代码
System.out.println("Monkey Move");
}
}


抽象装饰角色“七十二变”

public class Change implements TheGreatestSage {
private TheGreatestSage sage;
public Change(TheGreatestSage sage){
this.sage = sage;
}
@Override
public void move() {
// 代码
sage.move();
}
}


具体装饰角色“鱼儿”

public class Fish extends Change {

public Fish(TheGreatestSage sage) {
super(sage);
}

@Override
public void move() {
// 代码
System.out.println("Fish Move");
}
}
具体装饰角色“鸟儿”

public class Bird extends Change {

public Bird(TheGreatestSage sage) {
super(sage);
}

@Override
public void move() {
// 代码
System.out.println("Bird Move");
}
}
客户端类
public class Client {
public static void main(String[] args) {
TheGreatestSage sage = new Monkey();
// 第一种写法
TheGreatestSage bird = new Bird(sage);
TheGreatestSage fish = new Fish(bird);
// 第二种写法
//TheGreatestSage fish = new Fish(new Bird(sage));
fish.move();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: