结构图:
实现:
1 abstract public class Component { 2 abstract public void operation(); 3 }
public class ConcreteComponent extends Component { @Override public void operation() { System.out.println("具体操作"); } }
1 public class Decorator extends Component{ 2 protected Component component; 3 4 public void setComponent(Component c) 5 { 6 component = c; 7 } 8 9 @Override 10 public void operation() { 11 if (component != null) 12 component.operation(); 13 } 14 15 }
1 public class ConcreteDecoratorA extends Decorator{ 2 3 @Override 4 public void operation() { 5 super.operation(); 6 7 System.out.println("增加装饰A的操作"); 8 } 9 10 11 }
1 public class ConcreteDecoratorB extends Decorator{ 2 3 @Override 4 public void operation() { 5 super.operation(); 6 7 System.out.println("增加装饰B的操作"); 8 } 9 10 11 }
1 public class Client { 2 public static void main(String[] args) 3 { 4 ConcreteComponent cc = new ConcreteComponent(); 5 ConcreteDecoratorA cda = new ConcreteDecoratorA(); 6 ConcreteDecoratorB cdb = new ConcreteDecoratorB(); 7 8 cda.setComponent(cc); 9 cdb.setComponent(cda); 10 cdb.operation(); 11 12 } 13 }
应用场景:
适应于给一个对象动态添加额外的功能。