模式介绍

装饰器模式是一种结构型设计模式,它允许您通过将对象放入包含行为的特殊封装对象中来为原对象增加新的行为。装饰器模式提供了子类继承的替代方案。

使用场景

  • 当您需要在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责时
  • 当您需要给对象添加的功能,这些功能可以动态地撤销时
  • 当您需要在不影响现有代码的情况下,给对象添加新的功能时

代码示例

// 组件接口
public interface Component {
    void operation();
}

// 具体组件
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("具体组件的操作");
    }
}

// 装饰器基类
public abstract class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
    }
}

// 具体装饰器
public class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedBehavior();
    }

    private void addedBehavior() {
        System.out.println("装饰器添加的行为");
    }
}

优缺点

优点

  • 比继承更灵活
  • 可以动态地增加或删除对象的职责
  • 装饰器模式比继承更容易扩展功能

缺点

  • 会产生很多小类
  • 装饰器模式比继承更加灵活,同时也意味着更加容易出错
  • 对于多次装饰的对象,调试时寻找错误可能会变得困难