定义:动态地给一个对象加入一些额外的职责,就添加功能来说,装饰模式比生成子类更为灵活。
结构图:
演示样例代码:
public abstract class Component { public abstract void operation(); } public class ConcreteComponent extends Component{ @Override public void operation() { // TODO Auto-generated method stub System.out.println("详细对象操作!"); } } public class ConcreteDecoratorB extends Decorator { @Override public void operation() { // TODO Auto-generated method stub super.operation(); System.out.println("详细装饰对象B的操作"); } private void AddedBehavior() { System.out.println("我是B操作"); } } public class ConcreteDecoratorA extends Decorator { private String addedState; @Override public void operation() { // TODO Auto-generated method stub super.operation(); addedState = "New State"; System.out.println("详细装饰对象A的操作"); } }client代码例如以下所看到的:
public class Client { public static void main(String[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.setComponent(c); d2.setComponent(d1); d2.operation(); // d1.setComponent(d2); // d1.operation(); } }执行结果例如以下:
详细对象操作!
详细装饰对象A的操作
详细装饰对象B的操作