Java设计模式--装饰模式(Decorator)

概述


  • 装饰模式可以在不改变一个对象本身功能的基础上给对象增加额外的新行为; 装饰模式是一种用于替代继承的技术,它通过一种无须定义子类的方式来给对象动态增加职责,使用对象之间的组合关系取代类之间的继承关系。在装饰模式中引入了装饰类,在装饰类中既可以调用待装饰的原有类的方法,还可以增加新的方法,以扩充原有类的功能。
  • 定义:动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。
  • 装饰模式是一种对象结构型模式。
  • 学习难度:★★★☆☆
  • 使用频率:★★★☆☆

优缺点


  • 优点
    • 解耦装饰者和被装饰者
    • 是继承的一种替代方式,实现的还是is-a关系
    • 装饰者可以方便扩展具体装饰者类
  • 缺点
    • 装饰层多了,降低可读性

类图


Java设计模式--装饰模式(Decorator)

组成角色


  • 抽象构件(Component)
  • 具体构件(ConcreteComponent)
  • 装饰角色(Decorator)
  • 具体装饰角色(ConcreteDecorator)

Code Example


抽象构件(Component)
/**
 * 抽象构件角色(Component):定义一个抽象接口,以规范准备接收附加责任的对象。
 * 
 * @author yanbin
 * 
 */
public interface Component {

   public void operation();

}
具体构件(ConcreteComponent)
/**
 * 具体构件角色(Concrete Component):这是被装饰者,定义一个将要被装饰增加功能的类。
 * 
 * @author yanbin
 * 
 */
public class ConcreteComponent implements Component {

   @Override
   public void operation() {
      System.out.println("具体对象的操作!");
   }

}
装饰角色(Decorator)
聚合Component
聚合具体构建接口、并调用接口方法,保持原有的功能
集成抽象装饰者,super父方法的同时增加额外的职责方法
/**
 * 装饰角色(Decorator):持有一个构件对象的实例,并定义了抽象构件定义的接口。
 * 
 * @author yanbin
 * 
 */
public class Decorator implements Component {

   private Component component;

   @Override
   public void operation() {
      if (null != component) {
         component.operation();
      }
   }

   public void setComponent(Component component) {
      this.component = component;
   }

}
具体装饰角色(ConcreteDecorator)
/**
 * 具体装饰角色(Concrete Decorator):负责给构件添加增加的功能。
 * 
 * @author yanbin
 * 
 */
public class ConcreteDecoratorA extends Decorator {

   @Override
   public void operation() {
      super.operation();
      addState();
      System.out.println("具体装饰对象A的操作!");
   }

   /**
    * 区别B的A类独有的装饰
    */
   private void addState() {
      System.out.println("add new state");
   }

}
/**
 * 具体装饰角色(Concrete Decorator):负责给构件添加增加的功能。
 * 
 * @author yanbin
 * 
 */
public class ConcreteDecoratorB extends Decorator {

   /** 设置一个变量,用于区别A */
   private String state;

   @Override
   public void operation() {
      super.operation();
      state = "new state";
      System.out.println("具体装饰对象B的操作:" + state);
   }

}
客户端
/**
 * 装饰者模式:装饰模式(Decorator)也叫包装器模式(Wrapper)。动态地给一个对象添加一些额外的职责。<br>
 * Decorator 模式相比 生成子类更为灵活。<br>
 * 组成:抽象构件角色(Component)、
 * 具体构件角色(ConcreteComponent)、装饰角色(Decorator)、具体装饰角色(ConcreteComponent)
 * 
 * @author yanbin
 * 
 */
public class DecoratorPattern {

   public static void main(String[] args) {
      Component component = new ConcreteComponent();
      Decorator decoratorA = new ConcreteDecoratorA();
      Decorator decoratorB = new ConcreteDecoratorB();
      component.operation();
      decoratorA.operation();
      decoratorB.operation();
   }

}