思想本质:动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
设计要点:
1. 装饰者和被装饰对象有相同的超类型。
2. 可以用一个或多个装饰者包装一个对象。
3. 装饰者可以在所委托被装饰者的行为之前或之后,加上自己的行为,以达到特定的目的。
4. 对象可以在任何时候被装饰,所以可以在运行时动态的,不限量的用你喜欢的装饰者来装饰对象。
5. 装饰模式中使用继承的关键是想达到装饰者和被装饰对象的类型匹配,而不是获得其行为。
模式类结构图:
下面我参考大话设计模式里面给人穿衣服的例子用c++来实现该模式。人的衣服可以有coat, shirt, skirt等,为了能动态地给人穿衣服,应该使用装饰者模式。具体实现如下:
1: #include <iostream>
2: #include <string>
3:
4: using namespace std;
5:
6: // Person class, which may need to be decorated
7: class Person
8: {
9: private:
10: string name;
11: public:
12: virtual void Show()
13: {
14: cout<<name<<"\t";
15: // do nothing else here
16: }
17:
18: Person(string name)
19: {
20: this->name = name;
21: }
22:
23: Person()
24: {
25:
26:
27: }
28:
29: ~Person()
30: {
31:
32: }
33: };
34:
35: // Decorator class
36: class Decorator: public Person
37: {
38: private:
39: Person* m_pPerson;
40:
41: public:
42: void Decarate(Person* p);
43: virtual void Show();
44: ~Decorator()
45: {
46:
47: }
48: };
49:
50:
51: void Decorator::Decarate(Person* p)
52: {
53: m_pPerson = p;
54: }
55:
56: void Decorator::Show()
57: {
58: m_pPerson->Show();
59: }
60:
61:
62: // Coat class, which is a decorator of Person
63: class Coat: public Decorator
64: {
65: public:
66: virtual void Show();
67:
68: };
69:
70: void Coat::Show()
71: {
72: Decorator::Show();
73: cout<<"wear coat."<<endl;
74: }
75:
76:
77:
78: // Skirt class, which is also a decorator of Person
79: class Skirt: public Decorator
80: {
81: public:
82: virtual void Show();
83: };
84:
85: void Skirt::Show()
86: {
87: Decorator::Show();
88: cout<<"wear skirt."<<endl;
89: }
客户代码如下:
1: #include <iostream>
2:
3: #include "simpleFactory.h"
4: #include "strategy.h"
5: #include "decorator.h"
6:
7: using namespace std;
8:
9:
10: int main(int argc, char* argv[])
11: {
12: // client code
13: Person xiaoli("xiaoli");
14: Coat coat;
15: Skirt skirt;
16:
17: coat.Decarate(&xiaoli);
18: coat.Show();
19:
20: skirt.Decarate(&xiaoli);
21: skirt.Show();
22:
23: return 0;
24: }
输出如下:
1: xiaoli wear coat.
2: xiaoli wear skirt.通过用不同的装饰对象来装饰xiaoli,xiaoli有了不同的穿着。这就是装饰者模式
没有评论:
发表评论