zoukankan      html  css  js  c++  java
  • 装饰器模式设计模式

    一.装饰者模式定义:
    ​动态地为一个对象添加一些额外的职责,若要扩展一个对象的功能,装饰者提供了比继承更有弹性的替代方案。
    模式的结构图:

    二.模式包含角色 :
    抽象构件类(Component):给出一个抽象的接口,用以规范准备接收附加责任的对象
    具体构件类(ConcreteComponent):定义一个具体的准备接受附加责任的类,其必须实现Component接口。
    装饰者类(Decorator):持有一个构件(Conponent)对象的实例,并定义一个和抽象构件一致的接口。
    具体装饰者类(ConcreteDecoratator):定义给构件对象“贴上”附加责任。

    三.使用场景:
    I/O流,数据源包装 ,Spring 中用到的装饰器模式在类名上有两种表现:一种是类名中含有 Wrapper,另一种是类名中含有Decorator。

    ①.用于拓展一个类的功能或者给一个类添加附加职责
    ②.动态的给一个对象添加功能,这些功能可以再动态的撤销。
    ③.需要为一批的兄弟类进行改装或加装功能。

    四.装饰模式的优缺点
    优点:
    1、装饰器是继承的有力补充,比继承灵活,不改变原有对象的情况下动态地给一个对象扩展功能,即插即用。
    2、通过使用不同装饰类以及这些装饰类的排列组合,可以实现不同效果。
    3、装饰器完全遵守开闭原则。
    缺点:
    1、会出现更多的代码,更多的类,增加程序复杂性。
    2、动态装饰时,多层装饰时会更复杂。追踪代码更难看点

    五.代码如下所示:
    抽象构件角色

    public interface Component {
        public void sampleOpreation();
    }

     具体构件角色:

    public class ConcreteComponent implements Component {
        @Override
        public void sampleOpreation() {
            // TODO 完成相关的业务代码
        }
    }

     装饰角色

    public class Decorator implements Component {
        private Component component;
        
        public Decorator(Component component) {
            this.component = component;
        }
        
        @Override
        public void sampleOpreation() {
            //委派给构件
            component.sampleOpreation();
        }
    
    }

     具体装饰角色

    public class ConcreteDecoratorA extends Decorator {
        public ConcreteDecoratorA(Component component) {
            super(component);
        }
        
        @Override
        public void sampleOpreation() {
            super.sampleOpreation();
            //TODO 完成相关的业务代码
        }
    }
    public class ConcreteDecoratorB extends Decorator {
        public ConcreteDecoratorB(Component component) {
            super(component);
        }
        
        @Override
        public void sampleOpreation() {
            super.sampleOpreation();
            //TODO 完成相关的业务代码
        }
    }

    参考网站:https://www.jianshu.com/p/d80b6b4b76fc

    https://www.cnblogs.com/yssjun/p/11110013.html

    郭慕荣博客园
  • 相关阅读:
    Embeded Linux 之 PHY
    Embeded Linux之网络子系统
    语言之内联函数
    Embeded Linux之海思UART
    Windows 之samba问题
    Embeded linux 之 CIFS 文件操作源码分析
    zookeeper 都有哪些使用场景?
    如何保证分布式系统中接口调用的顺序性?
    分布式系统中接口的幂等性该如何保证?比如不能重复扣款?
    Redis 的并发竞争问题是什么?如何解决这个问题?了解 redis 事务的 CAS 方案吗?
  • 原文地址:https://www.cnblogs.com/jelly12345/p/14734802.html
Copyright © 2011-2022 走看看