zoukankan      html  css  js  c++  java
  • 【设计模式】装饰者模式

    简介

    将核心功能和装饰功能分离, 为已有功能动态新增功能。

    详述

    装饰者模式英文翻译:Decorator。

    装饰者模式类图

    component:抽象接口类。

    concretecomponent:具体的component类,实现核心功能,也是待添加功能的对象。

    decorator:装饰者抽象类,继承自component抽象接口类,实际调用component类的operation方法,提供设置待添加职责对象接口setcomponent。

    concretecomponentA:具体的装饰者类A,重写component的operatiron方法 ,concretecomponentA的operation调用ptrcomponent->operation后添加新的职责。

    包装过程

    concretecomponent* cct = new concretecomponent;

    concretedecoratorA* cda = new concretedecoratorA;

    concretedecoratorB* cdb = new concretedecoratorB;

    cda.setcomponent(cct);

    cdb.setcomponent(cda);

    cdb.operation();

    包装后的cdb.operation就依次执行了cct的operation、cda的operation、cdb的operation,为cct额外增加了cda、cdb两个职责。 

    特性及关键点

    装饰者对象A和B都通过setcomponent来对对象进行包装,每个装饰对象的实现和使用这个对象分开,A和B类均只需关注自己要增加的额外职责,不需要关心如何将职责增加到对象上。

    把装饰功能从类的中去除,简化原有的类,把核心职责和装饰功能分开,去除相关类中重复的装饰逻辑。

    小纪

    打着瞌睡学完了装饰者模式,好崇拜前辈们,可以说完破了我以前的拙劣设计。 

  • 相关阅读:
    this指向问题
    b继承a的函数
    如何解决跨域问题
    事件冒泡和阻止事件冒泡
    Spring5(二)——IOC
    MySQL基础(四)——
    MySQL基础(二)——常用命令
    MySQL基础(一)——入门
    Linux(二)——常用命令
    Linux(一)——简介
  • 原文地址:https://www.cnblogs.com/learn-my-life/p/3827313.html
Copyright © 2011-2022 走看看