谢谢博主:http://chenhua-1984.iteye.com/blog/565629的分享
这里记下代码,方便以后学习
Decorator装饰器,顾名思义,就是动态地给一个对象添加一些额外的职责,就好比为房子进行装修一样。因此,装饰器模式具有如下的特征:
它必须具有一个装饰的对象。
它必须拥有与被装饰对象相同的接口。
它可以给被装饰对象添加额外的功能。
用一句话总结就是:保持接口,增强性能。
装饰器通过包装一个装饰对象来扩展其功能,而又不改变其接口,这实际上是基于对象的适配器模式的一种变种。它与对象的适配器模式的异同点如下。
相同点:都拥有一个目标对象。
不同点:适配器模式需要实现另外一个接口,而装饰器模式必须实现该对象的接口。
以下是代码片度
Soucable.java
package decorator;
public interface Soucable {
public void operation();
}
package decorator;
public class Source implements Soucable {
public void operation(){
System.out.println("这是原始的操作方法");
}
}
package decorator;
public class Decorator1 implements Soucable {
private Soucable souc = null;
public Decorator1(Soucable souc){
super();
this.souc = souc;
}
public void operation() {
System.out.println("第一个装饰器的前面");
souc.operation();
System.out.println("第一个装饰器的后面");
}
}
package decorator;
public class Decorator2 implements Soucable{
private Soucable souc = null;
public Decorator2(Soucable souc){
super();
this.souc = souc;
}
public void operation() {
System.out.println("第二个装饰器的前面");
souc.operation();
System.out.println("第二个装饰器的后面");
}
}
package decorator;
public class Decorator3 implements Soucable{
private Soucable souc = null;
public Decorator3(Soucable souc){
super();
this.souc = souc;
}
public void operation() {
System.out.println("第三个装饰器的前面");
souc.operation();
System.out.println("第三个装饰器的后面");
}
}
package decorator;
public class Test {
public static void main(String[] args) {
Soucable souc = new Decorator1(new Decorator2(new Decorator3(new Source())));
souc.operation();
}
}
结果:
第一个装饰器的前面
第二个装饰器的前面
第三个装饰器的前面
这是原始的操作方法
第三个装饰器的后面
第二个装饰器的后面
第一个装饰器的后面