设计模式(9/23) - 装饰器模式

25 阅读3分钟

装饰器模式

1 概述

  • 装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许向一个现有的对象添加新的功能,同时又不改变其结构。装饰器模式通过创建一个装饰类来包裹原始类,并在保留类方法签名的前提下提供附加功能。
  • 这种模式创建了一个装饰器类,用来包装原始类,并在不改变原始类的情况下提供额外的功能。

2 优缺点及应用场景

2.1 优点

  • 1)灵活性高:可以在运行时动态地扩展一个对象的功能,添加和删除装饰器不会影响其他装饰器。
  • 2)遵循开闭原则:可以在不修改现有代码的基础上扩展对象的功能。
  • 3)职责分离:不同的装饰类可以负责不同的功能,符合单一职责原则。

2.2 缺点

  • 1)增加复杂性:由于使用了多个装饰类,系统可能会变得复杂,增加了调试的难度。
  • 2)创建较多的对象:装饰器模式会导致设计中创建大量的装饰器对象,影响性能。

2.3 应用场景

  • 1)功能扩展:在不修改现有代码的情况下,向现有对象添加新的功能。
  • 2)动态变化:需要在运行时根据需要动态地添加或删除功能。
  • 3)多功能组合:需要将多个功能组合在一起,形成复杂的功能。

3 结构

  • 1)组件(Component):定义一个对象接口,可以给这些对象动态地添加职责。
  • 2)具体组件(ConcreteComponent):实现组件接口的类。
  • 3)装饰器(Decorator):持有一个组件对象,并定义一个与组件接口一致的接口。
  • 4)具体装饰器(ConcreteDecorator):实现装饰器接口,并向组件添加额外的功能。

4 实现

4.1 UML 类图

装饰器模式.jpg

4.2 代码示例

// 创建一个接口
interface Shape {
  void draw();
}

// 创建实现接口的实体类:长方形
class Rectangle implements Shape {
  @Override
  public void draw() {
    System.out.println("Shape: Rectangle");
  }
}

// 创建实现接口的实体类:圆形
class Circle implements Shape {
  @Override
  public void draw() {
    System.out.println("Shape: Circle");
  }
}

// 创建实现了 Shape 接口的抽象装饰类
abstract class ShapeDecorator implements Shape {
  protected Shape decoratedShape;

  public ShapeDecorator(Shape decoratedShape) {
    this.decoratedShape = decoratedShape;
  }

  public void draw() {
    decoratedShape.draw();
  }
}

// 创建扩展了 ShapeDecorator 类的实体装饰类
class RedShapeDecorator extends ShapeDecorator {
  public RedShapeDecorator(Shape decoratedShape) {
    super(decoratedShape);
  }

  @Override
  public void draw() {
    decoratedShape.draw();
    setRedBorder(decoratedShape);
  }

  private void setRedBorder(Shape decoratedShape) {
    System.out.println("Border Color: Red");
  }
}

// 使用示例
public class DecoratorPatternDemo {
  public static void main(String[] args) {
    // 使用 RedShapeDecorator 来装饰 Shape 对象
    Shape circle = new Circle();
    ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
    ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
    // Shape redCircle = new RedShapeDecorator(new Circle());
    // Shape redRectangle = new RedShapeDecorator(new Rectangle());
    System.out.println("Circle with normal border");
    circle.draw();

    System.out.println("\nCircle of red border");
    redCircle.draw();

    System.out.println("\nRectangle of red border");
    redRectangle.draw();
  }
}
  • 执行程序,输出结果:
Circle with normal border
Shape: Circle

Circle of red border
Shape: Circle
Border Color: Red

Rectangle of red border
Shape: Rectangle
Border Color: Red

5 总结

  • 装饰器模式通过创建装饰类在不改变现有对象结构的情况下动态地扩展其功能,提供了比继承更灵活的功能扩展方式。它适用于需要在运行时动态地扩展对象功能的场景。虽然装饰器模式提高了系统的灵活性和可扩展性,但也增加了系统的复杂性。通过合理地使用装饰器模式,可以有效地管理和扩展对象功能,满足复杂应用的需求。