装饰器模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活。
它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码可以在运行时根据需要有选择地,有根据地使用装饰功能包装对象。
//被装饰对象基类
public interface Compent {
public void operation();
}
//具体被装饰对象
public class RealCompent implements Compent {
@Override
public void operation() {
System.out.println("执行具体操作");
}
}
//装饰器基类,持有被装饰对象
public class Decorator implements Compent{
Compent compent;
public Decorator(Compent compent) {
this.compent = compent;
}
@Override
public void operation() {
System.out.println("我是装饰器基类");
compent.operation();
}
}
//装饰器1
public class Decorator1 extends Decorator {
private String str = "装饰器装饰上的字符串";
public Decorator1(Compent compent) {
super(compent);
}
public void DoFirst() {
System.out.println("执行前的装饰操作A");
}
public void DoLast() {
System.out.println("执行后的装饰操作B");
}
@Override
public void operation() {
System.out.println(str);
DoFirst();
super.operation();
DoLast();
}
public static void main(String[] args) {
Compent realCompent= new RealCompent();
Decorator1 decorator1 = new Decorator1(realCompent);
decorator1.operation();
}
}
输出
装饰器装饰上的字符串
执行前的装饰操作A
我是装饰器基类
执行具体操作
执行后的装饰操作B