C++装饰者模式

代码转自 http://blog.csdn.net/wuzhekai1985

装饰者模式:动态地给一个对象添加一些额外的职责,就增加功能来说,为实物已有的功能添加额外的新功能,组合成整体。有时我们希望给某个对象而不是整个类添加一些功能。

即DecotatorPhoneA::Show()函数在有Show()的情况下,添加Add()函数
1、为什么Decorator装饰者需要继承Phone类,而不是其他的类,或者不继承?
作为装饰者,仍相当于跟NokiaPhone类同级,只是在这种类的某个功能上添加新的功能,
这样可以由多态通过Phone调用派生类Show函数时,调用到装饰者派生类函数

2、为什么不直接在派生类中添加功能?
装饰者派生类与实物派生类会构成(n*n)中可能,有新的装饰需要添加时,n个实物派生类都需要添加

 

代码如下:

  1 #include "stdafx.h"
  2 #include <string>
  3 #include <iostream>
  4 using namespace std;
  5 
  6 class Phone
  7 {
  8 public:
  9     virtual void Show() = 0;
 10 };
 11 
 12 class iPhone : public Phone
 13 {
 14 public:
 15     iPhone(string strName) : m_strName(strName){}
 16     ~iPhone(){}
 17 
 18 public:
 19     void Show()
 20     {
 21         cout<<m_strName<<endl;
 22     }
 23 
 24 private:
 25     string m_strName;
 26 };
 27 
 28 class NokiaPhone : public Phone
 29 {
 30 public:
 31     NokiaPhone(string strName):m_strName(strName){}
 32     ~NokiaPhone(){}
 33 
 34 public:
 35     void Show()
 36     {
 37         cout<<m_strName<<endl;
 38     }
 39 
 40 private:
 41     string m_strName;
 42 };
 43 
 44 class Decorator : public Phone
 45 {
 46 public:
 47     Decorator(Phone* phone) : m_pPhone(phone){}
 48     ~Decorator(){}
 49 
 50 public:
 51     virtual void Show()
 52     {
 53         m_pPhone->Show();
 54     }
 55 
 56 private:
 57     Phone *m_pPhone;
 58 };
 59 
 60 class DecotatorPhoneA : public Decorator
 61 {
 62 public:
 63     DecotatorPhoneA(Phone* phone):Decorator(phone){}
 64     ~DecotatorPhoneA(){}
 65 
 66 public:
 67     void Show()    
 68     {
 69         Decorator::Show();    //已有功能
 70         AddDecotator();      //添加新装饰
 71     }
 72 
 73 private:
 74     inline void AddDecotator()            //添加额外装饰
 75     {
 76         cout<<"DecotatorPhoneA 装饰"<<endl;
 77     }
 78 };
 79 
 80 class DecotatorPhoneB : public Decorator
 81 {
 82 public:
 83     DecotatorPhoneB(Phone* phone):Decorator(phone){}
 84     ~DecotatorPhoneB(){}
 85 
 86 public:
 87     void Show()    
 88     {
 89         Decorator::Show();
 90         AddDecotator();
 91     }
 92 
 93 private:
 94     inline void AddDecotator()            //添加额外装饰
 95     {
 96         cout<<"DecotatorPhoneB 装饰"<<endl;
 97     }
 98 };
 99 
100 
101 int _tmain(int argc, _TCHAR* argv[])
102 {
103     Phone *phone = new iPhone("ipone");
104     if (NULL!=phone)
105     {
106         Phone *pDePhone = new DecotatorPhoneA(phone);
107         if (NULL!=pDePhone)
108         {
109             pDePhone->Show();
110 
111             delete pDePhone;
112             pDePhone = NULL;
113         }
114 
115         delete phone;
116         phone = NULL;
117     }
118 
119     return 0;
120 }

  通过组合能够方便的将装饰者A与B添加到实物ipone与Nokia上。

posted @ 2017-10-25 17:23  风狼啸天  阅读(401)  评论(0编辑  收藏  举报