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类均只需关注自己要增加的额外职责,不需要关心如何将职责增加到对象上。

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

    小纪

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

  • 相关阅读:
    Linux下的ping命令
    git stash
    ansiable
    「疫期集训day4」硝烟
    「线段树」「单点修改」洛谷P1198 [JSOI2008]最大数
    「状压DP」「暴力搜索」排列perm
    「疫期集训day3」要塞
    「疫期集训day2」高地
    「疫期集训day1」无言
    「区间DP」「洛谷P1043」数字游戏
  • 原文地址:https://www.cnblogs.com/learn-my-life/p/3827313.html
Copyright © 2011-2022 走看看