装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
适用范围:
#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. "; } };
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. "); } };
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; }
设计模式初探3——装饰者模式(Observer Pattern)
原文地址:http://blog.csdn.net/cloud_castle/article/details/40743293