C++装饰器模式

UML图:

 1 #include <iostream>
 2 #include <string>
 3 #include <windows.h>
 4 using namespace std;
 5 //抽象类Cake
 6 class Cake
 7 {
 8 public:
 9     string m_name;
10     //如果一个类中有纯虚函数
11     //那么这个类无法被实例化
12     //需要先继承再实例化
13     virtual void show() = 0;
14 };
15 class ConcreteCake:public Cake
16 {
17 public :
18     ConcreteCake()
19     {
20         m_name = "原始蛋糕";
21     }
22 
23     virtual void show()
24     {
25         cout << m_name.c_str() << endl;
26     }
27 
28 };
29 //抽象类Decorator
30 class Decorator :public Cake
31 {
32 public :
33     Cake * pCake;
34     virtual void show() = 0;
35 };
36 //具体奶油类
37 class DecCream :public Decorator
38 {
39 public :
40     DecCream(Cake * cake)
41     {
42         pCake = cake;
43     }
44 
45     void show()
46     {
47         pCake->show();
48         cout << "加奶油" << endl;
49     }
50 
51 
52 };
53 //具体饼干类
54 class DecBiscuits :public Decorator
55 {
56 public:
57     DecBiscuits(Cake * cake)
58     {
59         pCake = cake;
60     }
61 
62     void show()
63     {
64         pCake->show();
65         cout << "加饼干" << endl;
66     }
67 
68 
69 };
70 int main()
71 {
72     //原始蛋糕:先加奶油,再加饼干
73     //ConcreteCake *  pOrinCake = new  ConcreteCake() ;
74     //DecCream * pCream = new DecCream(pOrinCake);
75     //DecBiscuits * pBiscuits = new DecBiscuits(pCream);
76     //pBiscuits->show();
77 
78     //原始蛋糕:先加饼干,再加奶油
79     ConcreteCake *  pOrinCake = new  ConcreteCake() ;
80     DecBiscuits * pBiscuits = new DecBiscuits(pOrinCake);
81     DecCream * pCream = new DecCream(pBiscuits);
82     pCream->show();
83     //可以看到上面创建了三个实例,单步调试可以观察到逐个调用实例show()方法的过程
84     system("pause");
85 }

装饰器模式的特点就是:

根据这个例子来说,重写show()的时候,会调用需要被装饰的类的原本的show(),在原来的show()的基础上再添加上自己的东西.

更通用地说,就是为方法增加新的功能,其实现机制是重写这个方法,并在重写的过程当中调用原本的方法并添加新的功能.

不改变原来方法的内容,只增不减.

优点:

可以根据自己的需要选择自己需要的部件(可以不按顺序地,无相互联系地)进行组合,以达到对象的方法随机应变拓展的效果,比继承来得更加灵活,而且更偏向于组合的思维模式.

原文地址:https://www.cnblogs.com/virgildevil/p/11588911.html