装饰模式

装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
 
Component定义一个对象接口,可以给这些对象动态的添加职责。
ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。
Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在。
ConcreteDecoratorA和ConcreteDecoratorB是具体装饰对象,起到给Component添加职责的功能。
 
abstract class Component{
     public abstract void Operation();
}
class ConcreteComponent extend Component{
     public Operation(){
         console.log(“具体对象操作”);
     }
}
abstract class Decorator extend Component{
     protected Component component;
     public setComponent(Component component){
          this.component = component;
     }
     public Operation(){
          if(this.component != null){
               component.Operation();
          }
     }
}
class ConcreteDecoratorA extend Decorator{
     private string addedState;
     public Operation(){
          super.Operation();
          addedState = "new State";
          console.log("具体装饰对象A操作");
     }
}
class ConcreteDecoratorB extend Decorator{
     public Operation(){
          super.Operation();
          addedBehavior();
          console.log("装饰对象B的操作");
     }
     private addedBehavior(){}
}
class Main{
     ConcreteComponent c = new ConcreteComponent();
     ConcreteDecoratorA d1 = new ConcreteDecoratorA();
     ConcreteDecoratorB d2 = new ConcreteDecoratorB();

     d1.setComponent(c);
     d2.setComponent(d1);
     d2.Operation();
}

  

 该模式利用setComponent来对对象进行包装,每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。
 
 
总结:装饰模式是为已有功能动态的添加更多功能的方式。
当系统需要新功能的时候,是向旧的类添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。
如果我们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所需要的装饰对象,因为,当需要执行特殊行为时,特护代码就可以在运行时根据需要有选择的、按顺序的使用装饰功能包装对象。
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/xiaohaoxuezhang/p/6768432.html