• 装饰器模式笔记


    定义

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

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

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

    使用

    其中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(); // 装饰后的方法
        }
    }

    总结

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

  • 相关阅读:
    【小程序】文本超出则省略号
    【wx小程序】读懂app.js
    【js】某字符串多次替换
    【小程序】本地资源图片无法通过 WXSS 获取
    【小程序】(一)注册开始小程序开发
    【小程序】配置本地接口开发
    【css】文本超出行数以省略号显示
    【webstorm】project目录树显示不出
    【Nodejs】Browsersync同步浏览器测试
    获取指定包名下继承或者实现某接口的所有类(扫描文件目录和所有jar)
  • 原文地址:https://www.cnblogs.com/zawier/p/6885446.html
Copyright © 2020-2023  润新知