java设计模式装饰者模式(简单笔记)

作用:  扩展对象的功能。
涉及角色:
   1 、抽象构件角色:定义一个抽象接口,来规范准备附加功能的类。
   2 、具体构件角色:将要被附加功能的类,实现抽象构件角色接口。
   3 、抽象装饰者角色:持有对具体构件角色的引用并定义与抽象构件角色一致的接口。
   4、具体装饰角色:实现抽象装饰者角色,负责为具体构件添加额外功能。
 
代码实例:
抽象构件角色java 代码
package decorator;    
public interface InterfaceComponent {   
    public void say();   
}    
具体构件角色java 代码
package decorator;    
public class Component implements InterfaceComponent{   
    public void say() {   
        System.out.println("Component.say():原组件的方法!");   
    }    
抽象装饰者角色java 代码
package decorator;    
public abstract class AbstractDecorator  implements   InterfaceComponent{   
         private InterfaceComponent   component;   
         public AbstractDecorator(InterfaceComponent   component){   
                  this.component = component;    
         }    
         protected void preSay(){};    //组件方法执行前预处理方法
         protected void afterSay(){};      //组件方法执行后处理方法         
         public void say(){   
                  preSay();    
                  component.say();    
                  afterSay();    
         };    
}    
具体装饰者二java 代码
package decorator;    
public class DecoratorTwo extends AbstractDecorator{   
      public DecoratorTwo(InterfaceComponent component) {   
           super(component);   
       }    
      protected void preSay(){     //根据需要重载模板类preSay()方法  
          System.out.println("DecoratorTwo.preSay():装饰者二的preSay()方法!");   
      }    
     protected void afterSay(){     //根据需要重载模板类afterSay()方法
         System.out.println("DecoratorTwo.afterSay():装饰者二的afterSay()方法!");    
   }    
}    
装饰者一java 代码
package decorator;    
public class DecoratorOne extends AbstractDecorator{   
       public DecoratorOne(InterfaceComponent component) {   
              super(component);   
       }    
       protected void preSay(){    //根据需要重载模板类preSay()方法   
             System.out.println("DecoratorOne.preSay():装饰者一的preSay()方法!");    
      }            
      protected void afterSay(){    //根据需要重载模板类afterSay()方法    
            System.out.println("DecoratorOne.afterSay():装饰者一的afterSay()方法!");   
     }    
      public static void main(String[] args) {    // 测试方法 
               InterfaceComponent interfaceComponent = new DecoratorTwo(new DecoratorOne(new Component()));   
               interfaceComponent.say();    
      }    
}    
控制台输出:
  1.          * 控制台输出:   
  2.          * DecoratorTwo.preSay():装饰者二的preSay()方法!   
  3.          * DecoratorOne.preSay():装饰者一的preSay()方法! 
  4.          * Component.say():原组件的方法!   
  5.          * DecoratorOne.afterSay():装饰者一的afterSay()方法! 
  6.          * DecoratorTwo.afterSay():装饰者二的afterSay()方法! 
 
4、优缺点
优点:1)提供比继承更多的灵活性 2)使用不同的装饰组合可以创造出不同行为的组合 3)需要的类的数目减少
缺点:1)灵活性带来比较大的出错性 2)产生更多的对象,给查错带来困难
 
原文地址:https://www.cnblogs.com/javawebsoa/p/3069892.html