装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
适用范围:
一种情况是,可能有大量独立的扩展。为支持每一种组合将产生大量的子类。使得子类数目呈爆炸性增长。
还有一种情况可能是由于类定义被隐藏,或类定义不能用于生成子类。
#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——装饰者模式(Decorator Pattern)
原文:http://www.cnblogs.com/lcchuguo/p/5059115.html