装饰模式

【1】什么是装饰模式?

装饰模式:动态地给一个对象添加一些额外的职责。

【2】装饰模式代码示例:

代码如下:

 1 #include <string>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 class Person
 6 {
 7 private:
 8     string m_strName;
 9 public:
10     Person(string strName)
11     {
12         m_strName = strName;
13     }
14 
15     Person(){}
16 
17     virtual void show()
18     {
19         cout << "装扮的是:" << m_strName << endl;
20     }
21 };    
22 
23 class Finery : public Person
24 {
25 protected:
26     Person *m_component;
27 public:
28     void decorate(Person* component)
29     {
30         m_component = component;
31     }
32     virtual void show()
33     {
34         m_component->show();
35     }
36 };
37 
38 class TShirts : public Finery
39 {
40 public:
41     virtual void show()
42     {
43         m_component->show();
44         cout << "T shirts" << endl;
45     }
46 };
47 
48 class BigTrouser : public Finery
49 {
50 public:
51     virtual void show()
52     {
53         m_component->show();
54         cout << "Big Trouser" << endl;
55     }
56 };
57 
58 int main()
59 {
60     Person *p = new Person("小李");
61     BigTrouser *bt = new BigTrouser();
62     TShirts *ts = new TShirts();
63         
64     bt->decorate(p);
65     ts->decorate(bt);
66     ts->show();
67 
68     return 0;
69 }
View Code

 

Good  Good  Study, Day  Day  Up.

顺序   选择   循环   总结

原文地址:https://www.cnblogs.com/Braveliu/p/3938662.html