• [工作中的设计模式]装饰模式decorator


    一、模式解析

     装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

    装饰模式的要点主要是:

    1、需要对已有对象扩展新的功能,又不希望改变原有对象接口;

    2、装饰者对象与原有对象需要继承相同接口,初始化装饰对象时将原有对象传入装饰对象;

    3、可以对一个对象定义多个装饰着对象,进行分别装饰或者组合装饰

    二、模式代码

    1、抽象接口

    package decorator.patten;
    
    public interface Component {
        public void operation();
    }

    2、定义被装饰对象

    package decorator.patten;
    
    public class ConcreteComponent implements Component {
    
        @Override
        public void operation() {
            System.out.println("我是被装饰对象,我执行了");
        }
    
    }

    3、定义装饰者对象A

    package decorator.patten;
    
    public class DecoratorA implements Component {
        Component component;
        public DecoratorA(Component component){
            this.component=component;
        }
        @Override
        public void operation() {
            System.out.println("我是装饰对象A,我在被装饰对象前增加打印");
            component.operation();
        }
    
    }

    4、定义装饰者对象B

    package decorator.patten;
    
    public class DecoratorB implements Component {
        Component component;
        public DecoratorB(Component component){
            this.component=component;
        }
        @Override
        public void operation() {
            component.operation();
            System.out.println("我是装饰对象b,我在被装饰对象后添加打印");
        }
    
    }

    5、定义客户端

    public class Client {
        public static void main(String[] args) {
            Component component=new DecoratorB(new DecoratorA(new ConcreteComponent()));
            component.operation();
        }
    }

    6、执行结果

    我是装饰对象A,我在被装饰对象前增加打印
    我是被装饰对象,我执行了
    我是装饰对象b,我在被装饰对象后添加打印

    三、说明

    1、装饰着模式可以为被装饰者添加新的功能,,将核心功能和装饰功能进行分离,比如日志打印,字符集处理等
    2、可以对对象进行多此装饰,装饰均会被执行
    3、示例中多次装饰没有顺序,但实际中往往会是有序的,比如数据加密和数据过滤,如果先加密再过滤就会出现问题
    4、装饰对象和被装饰对象均集成同一个接口,有时候为了简化,我们会将装饰对象直接集成被装饰对象,这就是子类重写父类方法达到扩展功能的
    四、应用场景

    装饰模式最典型的应用就是java IO中对inputstream和outputstream的装饰,例如

    dis = new DataInputStream(
                        new BufferedInputStream(
                                new FileInputStream("test.txt")
                        )
                );
  • 相关阅读:
    P1659 [国家集训队]拉拉队排练
    manacher小结
    P4555 [国家集训队]最长双回文串
    P3649 [APIO2014]回文串
    P3899 [湖南集训]谈笑风生
    插头dp练习
    luoguP3066 [USACO12DEC]逃跑的BarnRunning
    luoguP3769 [CH弱省胡策R2]TATT
    android 广播,manifest.xml注册,代码编写
    *.db-journal 是什么(android sqlite )数据库删除缓存
  • 原文地址:https://www.cnblogs.com/jyyzzjl/p/5194023.html
Copyright © 2020-2023  润新知