23种设计模式之装饰器模式
装饰器模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式比生成子类更加灵活。
package designMode.decorator; abstract class Component { public abstract void operation(); }
package designMode.decorator; class ConcreteComponent extends Component{ @Override public void operation() { System.out.println("具体对象的操作!"); } }
package designMode.decorator; class ConcreteDecoratorA extends Decorator{ private String addedState; @Override public void operation() { super.operation(); addedState="New State"; System.out.println("具体装饰对象A的操作!_"+addedState); } } class ConcreteDecoratorB extends Decorator{ @Override public void operation() { super.operation(); addedBehavior(); System.out.println("具体装饰对象B的操作!"); } private void addedBehavior(){ } }
package designMode.decorator; abstract class Decorator extends Component{ protected Component component; public void setComponent(Component component) { this.component = component; } @Override public void operation() { if(component!=null) component.operation(); } }
package designMode.decorator; public class Test { public static void main(String[] args) { ConcreteComponent cc = new ConcreteComponent(); ConcreteDecoratorA a = new ConcreteDecoratorA(); ConcreteDecoratorB b = new ConcreteDecoratorB(); a.setComponent(cc); b.setComponent(a); b.operation(); } }