装饰模式的特点:
(1) 装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。
(2) 装饰对象包含一个真实对象的引用(reference)
(3) 装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。
(4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。
在装饰模式中的各个角色有:
(1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
(2)具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
(3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
(4)具体装饰(Concrete Decorator)角色:负责给构 件对象添加上附加的责任。
Component->Human
public interface Human {
public void wear();
}
Concrete Component->Man
public class Man implements Human {
@Override
public void wear() {
System.out.println("给我穿各种颜色的衣服");
}
}
Decorator ->Decorator
public class Decorator implements Human {
private Human human;
public Decorator(Human human) {
this.human = human;
}
@Override
public void wear() {
human.wear();
}
}
Concrete Decorator->One/Two/Three
public class DecoratorOne extends Decorator {
public DecoratorOne(Human human) {
super(human);
}
public void wear() {
super.wear();
System.out.println("红色衣服");
}
}
public class DecoratorTwo extends Decorator {
public DecoratorTwo(Human human) {
super(human);
}
public void wear() {
super.wear();
System.out.println("绿色衣服");
}
}
public class DecoratorThree extends Decorator {
public DecoratorThree(Human human) {
super(human);
}
public void wear() {
super.wear();
System.out.println("蓝色衣服");
}
}
测试类->Test
public class Test {
public static void main(String[] args) {
// Human huge=new Man();
// Human one=new DecoratorOne(huge);
// Human two=new DecoratorTwo(one);
// Human three=new DecoratorThree(two);
Human three=new DecoratorThree(new
DecoratorTwo(new DecoratorOne(new Man())));
three.wear();
}
}
控制台输出:
给我穿各种颜色的衣服
红色衣服
绿色衣服
蓝色衣服
参考链接:
http://www.cnblogs.com/java-my-life/archive/2012/04/20/2455726.html
http://blog.youkuaiyun.com/jason0539/article/details/22713711