假设Source类是需要被装饰的类,Decorator类是一个提供装饰功能的类,Decorator动态为Source添加功能。
public interface Sourceable {
void method();
}
public class Source implements Sourceable{
@Override
public void method() {
System.out.println("Source method");
}
}
public class Decorator implements Sourceable {
private Sourceable source;
public Decorator(Sourceable source) {
this.source = source;
}
@Override
public void method() {
System.out.println("装饰前");
source.method();
System.out.println("装饰后");
}
}
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
} catch (Exception e) {
e.printStackTrace();
}
}
public Test() {
Sourceable source = new Source();
Sourceable obj = new Decorator(source);
obj.method();
}
}
输出:
装饰前
Source method
装饰后
Source里面的method方法功能得到修饰和增强。