装饰器模式笔记

定义

一种动态地往一个类中添加新的行为的设计模式。

在不改变任何底层代码的情况下,给对象赋予新的职责。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

就功能而言,装饰器模式相比生成子类更加灵活,这样可以给某个对象而不是整个类添加一些功能。

使用

其中Component为待装饰的接口,ConcreteComponent为具体的待装饰类,Decorator为装饰器类,其实现待装饰接口,并持有一个带装饰的接口,ConcreteDecorator为装饰器的具体实现类。

代码(Java)

// 待装饰的接口
public interface Component {
    void operation();
}
​
// 待装饰的具体类
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("This is ConcreteComponent");
    }
}
​
// 装饰器抽象类
public abstract class Decorator implements Component {
    private 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() {
        System.out.println("ConcreteDecorator对operation的包装1");
        super.operation();
        System.out.println("ConcreteDecorator对operation的包装结束");
    }
​
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        component.operation(); // 原本方法
​
        Component decoratorComponent = new ConcreteDecorator(component);
        decoratorComponent.operation(); // 装饰后的方法
    }
}

总结

装饰器模式动态的将责任附加的对象上。想要扩展功能,装饰器提供了有别于继承的另一种选择。其符合开-闭原则,对扩展开发,对修改关闭。

原文地址:https://www.cnblogs.com/zawier/p/6885446.html