[大话设计模式] 第6章: 装饰模式
2017-08-01 12:55
204 查看
装饰模式(Decorator)
装饰模式:动态的给一个对象添加一些额外的职能,把所需功能按顺序串联起来并进行控制。每个要装饰的功能放在单独的类中,并让这个类包装它所要修饰的对象。当需要执行特殊行为时,客户端就可以根据需要有选择的、有顺序的使用装饰功能包装对象了。
装饰模式有效的把类的核心职能和装饰功能区分开了,并且可以去除相关类中重复的装饰逻辑。
UML类图
Component:定义一个对象接口,可以给这些对象动态地添加职责;
ConcreteComponent:定义一个具体的Component,继承自Component,重写了Component类的虚函数;
Decorator:维持一个指向Component对象的指针,该指针指向需要被装饰的对象;并定义一个与Component接口一致的接口;
ConcreteDecorator:向组件添加职责。
装饰模式穿衣服举例
UML类图#include <iostream> class Person { public: virtual ~Person(){} virtual void show(){ } }; // 服饰类(Decorator) class Finery : public Person { public: Finery(Person *p): component(p){} void show() override {} protected: Person *component; }; class Tie : public Finery { public: Tie(Person *p): Finery(p){ } void show() override{ std::cout << "tie " << std::endl; component->show(); } }; class Suit : public Finery { public: Suit(Person *p): Finery(p){ } void show() override{ std::cout << "suit " << std::endl; component->show(); } }; class Shoes : public Finery { public: Shoes(Person *p): Finery(p){ } void show() override{ std::cout << "shoes " << std::endl; component->show(); } }; int main() { Person *xc = new Person(); Tie *t = new Tie(xc); Shoes *s = new Shoes(t); s->show(); delete xc; delete t; delete s; return 0; } /* 输出结果 shoes tie */
参考链接
大话设计模式C++源码: https://github.com/yogykwan/design-patterns-cpp相关文章推荐
- 《大话设计模式》之--第6章 穿什么有这么重要?----装饰模式
- 大话设计模式C++实现-第6章-装饰模式
- 第6章 穿什么有这么重要?-装饰模式 大话设计模式
- 《大话设计模式》之--第6章 穿什么有这么重要?----装饰模式
- 《大话设计模式》代码JAVA版-第6章 装饰模式
- 三、大话设计模式 之 装饰模式
- 《大话设计模式》——读后感 (3)穿什么有这么重要?——装饰模式之理解实例(2)
- 大话设计模式-装饰模式(C++)
- 《大话设计模式》读书笔记(C++代码实现) 第六章:装饰模式
- 大话设计模式-装饰模式
- 大话设计模式(Python版)--装饰器模式
- 大话设计模式之装饰模式
- 大话设计模式_装饰模式
- 大话设计模式笔记 装饰模式
- 《大话设计模式》读书笔记:装饰模式与均值计算实例
- 第6章 装饰模式
- 大话设计模式学习(一)----装饰模式
- 大话设计模式-Study-Tips-第三章-装饰模式