装饰者设计模式就是对原有的代码功能实现动态的扩展,优化增强功能的部分,相对于继承来说灵活性更高。
例子如下:
public Interface Source{
public void method();
}
public class FSource implements Source{
@Override
public void method(){
System.out.println("The First Source");
}
}
public class SSource implements Source{
private Source source;
public SSource(source){
}
@Override
public void method(){
System.out.println("Before the Source");
source.method();
System.out.println("After the Source");
}
}
Main{
Source source = new FSource();
Source sSource = new SSource(source);
sSource.method();
}
输出结果:
Before the Source
The First Source
After the Source