“动态的将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的扩展方案”。
**

1. 我们用个例子来说明下

我们想要一杯深培咖啡(被装饰对象,Component),这个咖啡需要加入摩卡(装饰者,Decorator奶泡(装饰者,Decorator)。加入不同的元素我们需要计算价格(Component Operation
有一个煎饼摊,人们去买煎饼(被装饰对象,Component,有些人要加火腿(装饰者,Decorator的,有些人要加鸡蛋(装饰者,Decorator的,有些人要加生菜(装饰者,Decorator的,或者全加。加了不同的材料,就有不同的烹饪方式(Component Operation

2. 实现

  1. Component

定义可以动态添加任务的对象的接口

  1. abstract class Component {
  2. public abstract void operation();
  3. }


  1. ConcreteComponent

定义一个要被装饰器装饰的对象

  1. class ConcreteComponent extends Component {
  2. public void operation(){
  3. System.out.println("ConcreteComponent say");
  4. }
  5. }


  1. Decorator

维护对组件对象和其子类组件的引用

  1. abstract class Decorator extends Component {
  2. protected Component component;
  3. public Decorator(Component component) {
  4. this.component = component;
  5. }
  6. public void operation(){
  7. component.operation();
  8. }
  9. }


  1. ConcreteDecorator

向组件添加新的职责

  1. class ConcreteDecoratorA extends Decorator {
  2. public ConcreteDecoratorA(Component component){
  3. super(component);
  4. }
  5. private void operationFirst(){
  6. System.out.println("operationFirst say");
  7. }
  8. private void operationLast(){
  9. System.out.println("operationLast say");
  10. }
  11. public void operation() {
  12. operationFirst();
  13. super.operation();
  14. operationLast();
  15. }
  16. //新功能
  17. public void anotherOperation() {
  18. System.out.println("another operation");
  19. }
  20. }

3. 优缺点

优点

  • 只关心自身核心业务,解耦。
  • 动态扩展。

    缺点

  • 功能扩展过多,势必产生大量的类,维护成本。

  • 多层装饰比较复杂。

装饰器模式在jdk中的使用:java.io类