设计模式初探3——装饰者模式(Decorator Pattern)
来源:互联网 发布:网络教育统考时间 编辑:程序博客网 时间:2024/05/22 00:11
装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
适用范围:
1. 需要扩展一个类的功能,或给一个类添加附加职责。
2. 需要动态的给一个对象添加功能,这些功能可以再动态的撤销。
3. 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。
4. 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。
UML图:
测试代码:
我们创建一个Toy抽象类,然后来生产不同的玩具,并为它加上各种功能。
#include <iostream>#include <string>using namespace std;class Toy {public: virtual string getDescription() = 0;};
class Duck : public Toy {public: string getDescription(){ return "I'm a simple Toy-Duck. "; }};
接着是装饰类的基类,它包含Toy基类的指针,以便访问到我们的玩具鸭:
class Decorator : public Toy {public: Decorator(Toy* t) : toy(t){}protected: Toy* toy;};
创建形状装饰者和发声装饰者:
class ShapeDecorator : public Decorator {public: ShapeDecorator(Toy* t) : Decorator(t){} string getDescription() { return toy->getDescription.append("Now I have new shape. "); }};
class SoundDecorator : public Decorator {public: SoundDecorator(Toy* t) : Decorator(t){} string getDescription() { return toy->getDescription.append("Now I can quack. "); }};
好了,我们在main函数中测试一下:
int main() { Toy *toy = new Duck(); cout << toy->getDescription(); toy = new ShapeDecorator(toy); cout << toy->getDescription(); toy = new SoundDecorator(toy); cout << toy->getDescription(); return 0; }
让我们再关注一条十分重要的设计原则:
对扩展开放,对修改关闭。
0 0
- 设计模式初探3——装饰者模式(Decorator Pattern)
- 设计模式笔记3:装饰者模式(Decorator Pattern)
- 设计模式 —— 装饰器模式(Decorator Pattern)
- Java设计模式——装饰模式(Decorator Pattern)
- 设计模式-装饰者模式(Decorator Pattern)
- 设计模式-装饰模式(Decorator Pattern)
- 设计模式(8)—— 装饰者模式(Decorator Pattern)
- 设计模式(9)——装饰者模式(Decorator Pattern)
- C#设计模式(9)——装饰者模式(Decorator Pattern)
- Java设计模式——装饰者模式(Decorator Pattern)
- C#设计模式(9)——装饰者模式(Decorator Pattern)
- 设计模式笔记之装饰者模式(Decorator Pattern)
- C#设计模式之装饰者模式(Decorator Pattern)
- 设计模式学习(五) -- 装饰者模式 Decorator Pattern
- 设计模式系列(三)装饰者模式(Decorator Pattern)
- Java设计模式-装饰者模式(Decorator Pattern)
- 设计模式总结之Decorator Pattern(装饰者模式)
- Java设计模式:装饰者模式(Decorator Pattern)
- 五十个UI设计资源网站
- IOS开发中MVC的理解
- 谈谈职业规划——CSDN对陈皓的采访
- [Erlang]如何利用Binary减少系统内存使用
- xcode6 使用MJRefresh,Too many arguments to function call, expected 0, have *
- 设计模式初探3——装饰者模式(Decorator Pattern)
- 关于NGUI
- 读取ebp值的两种方式
- enum和Enum区别
- 获取sybase数据库时间详解
- 浅谈ASP.NET的内部机制
- cocos2dx 3.2 自定义用rapidjson读取json数据
- Unity3D中所有特殊的文件夹
- IAR旧版本的工程在新版本上运行时,需要修改的地方