来自于《大话设计模式》
装饰模式(Decorator):动态地给一个对象添加额外的职责,就增加的功能来说,装饰模式比生成子类更为灵活。
UML 图:
代码实现 C++:
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class Person
6 {
7 private:
8 string name;
9 public:
10 Person() {}
11 Person(string n): name(n) {}
12 virtual void Show()
13 {
14 cout << "装饰的 " << name << endl;
15 }
16 };
17
18 class Finery: public Person
19 {
20 protected:
21 Person* component;
22 public:
23 void Decorate(Person* p)
24 {
25 component = p;
26 }
27 virtual void Show()
28 {
29 if (component != 0)
30 {
31 component->Show();
32 }
33 }
34 };
35
36 class TShirts: public Finery
37 {
38 public:
39 virtual void Show()
40 {
41 cout << "大 T 恤 ";
42 Finery::Show();
43 }
44 };
45
46 class BigTrouser: public Finery
47 {
48 public:
49 virtual void Show()
50 {
51 cout << "垮裤 ";
52 Finery::Show();
53 }
54 };
55
56 int main()
57 {
58 Person* p = new Person("Mark");
59 p->Show();
60
61 TShirts* t = new TShirts;
62 t->Decorate(p);
63 t->Show();
64
65 BigTrouser* b = new BigTrouser;
66 b->Decorate(t);
67 b->Show();
68
69 delete p;
70 delete t;
71 delete b;
72 }
posted on 2011-04-23 18:09
unixfy 阅读(112)
评论(0) 编辑 收藏 引用