初学设计模式之装饰者模式

 

装饰者模式的代码例子

 1 #include<iostream>
 2 using namespace std;
 3 class SelfAbstract
 4 {
 5 public:
 6     virtual void exec(){};
 7 };
 8 
 9 class Self:public SelfAbstract
10 {
11 public:
12     void exec()
13     {
14         cout<<"被装饰的本体"<<endl;
15     };
16 };
17 
18 class Decrator:public SelfAbstract
19 {
20 private:
21     SelfAbstract *m_selfAbstract;
22 public:
23     Decrator(SelfAbstract *selfAbstract)
24     {
25     m_selfAbstract=selfAbstract;
26     };
27     void exec()
28     {
29         m_selfAbstract->exec();
30     };
31 };
32 
33 class Decrator1:public SelfAbstract
34 {
35 private:
36     SelfAbstract *m_selfAbstract;
37 public:
38     Decrator1(SelfAbstract *selfAbstract)
39     {
40     m_selfAbstract=selfAbstract;
41     };
42     void exec()
43     {  
44         m_selfAbstract->exec();
45          cout<<"第一次装饰"<<endl;
46     };
47 };
48 
49 class Decrator2:public SelfAbstract
50 {
51 private:
52     SelfAbstract *m_selfAbstract;
53 public:
54     Decrator2(SelfAbstract *selfAbstract)
55     {
56     m_selfAbstract=selfAbstract;
57     };
58     void exec()
59     {   
60         m_selfAbstract->exec();
61         cout<<"第二次装饰"<<endl;
62     };
63 };
64 
65 int main()
66 {    Self m_Self;
67      Decrator m_Decrator(&m_Self);
68      Decrator1 m_Decrator1(&m_Decrator);
69      Decrator2 m_Decrator2(&m_Decrator1);
70      m_Decrator2.exec();
71 
72      getchar();
73      return 0;
74 };

 

posted on 2019-11-09 23:51  宏择一城  阅读(156)  评论(0编辑  收藏  举报

导航