装饰模式
装饰模式(Decorator),动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
示图代码如下:
1 public abstract class Component { 2 public abstract void operation(); 3 }
1 public class ConcreteComponent extends Component { 2 3 @Override 4 public void operation() { 5 System.out.println("具体对象的操作"); 6 } 7 8 }
1 public abstract class Decorator extends Component { 2 protected Component component; 3 4 public Component getComponent() { 5 return component; 6 } 7 8 public void setComponent(Component component) { 9 this.component = component; 10 } 11 12 @Override 13 public void operation() { 14 if(component!=null){ 15 component.operation(); 16 } 17 18 } 19 20 }
1 public class ConcreteDecoratorA extends Decorator { 2 String addedState; 3 @Override 4 public void operation() { 5 super.operation(); 6 addedState = "New State"; 7 System.out.println("具体装饰对象A的操作"); 8 } 9 10 }
1 public class ConcreteDecoratorB extends Decorator { 2 3 @Override 4 public void operation() { 5 super.operation(); 6 addedBehavior(); 7 System.out.println("具体装饰对象B的操作"); 8 } 9 10 private void addedBehavior(){ 11 System.out.println("--咕噜噜---"); 12 } 13 }
1 public class TestDecorator { 2 public static void main(String[] args) { 3 ConcreteComponent con = new ConcreteComponent(); 4 ConcreteDecoratorA d1 = new ConcreteDecoratorA(); 5 ConcreteDecoratorB d2 = new ConcreteDecoratorB(); 6 7 d1.setComponent(con); 8 d2.setComponent(d1); 9 d2.operation(); 10 11 } 12 }
具体对象的操作 具体装饰对象A的操作 --咕噜噜--- 具体装饰对象B的操作
装饰模式利用setComponent来对对象进行包装的,这样每个装饰对象实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,就不需要关心如何被添加到队形链当中
如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator,而可以把Decorator和ConcreteDecorator的责任合并成一个类。