意图
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
Source类是被装饰类,Decorator类是一个装饰类,可以为Source类动态的添加一些功能。
public interface Sourceable {
public void method();
}
public class Source implements Sourceable{
@Override
public void method() {
System.out.println("this is original method!");
}
}
public class Decorator implements Sourceable{
private Source source;
public Decorator(Source source){
super();
this.source = source;
}
@Override
public void method() {
System.out.println("before decorator!");
source.method();
System.out.println("after decorator!");
}
}
转自:http://blog.csdn.net/zhangerqing/article/details/8239539