装饰模式原理:给对象增加特性,这种特性是一种累加的效果
代码如下
#include <iostream> #include <string> #include <list> using namespace std; /************************************************************************/ /* 装饰模式的作用是为对象增加属性 */ /************************************************************************/ class Phone { public: Phone(string name):m_name(name) { } Phone() { } virtual void show(){} protected: string m_name; }; class IPhone:public Phone { public: IPhone(string name):Phone(name) { } virtual void show(){cout << m_name << "的装饰" <<endl;} }; class HTCPhone:public Phone { public: HTCPhone(string name):Phone(name) { } virtual void show(){cout << m_name << "的装饰" <<endl;} }; class DecoratorPhone:public Phone { public: DecoratorPhone(Phone *pPhone) { m_pPhone = pPhone; } virtual void show() { m_pPhone->show(); } protected: Phone *m_pPhone; }; class DecoratorPhoneA:public DecoratorPhone { public: DecoratorPhoneA(Phone *pPhone): DecoratorPhone(pPhone) { } virtual void show() { DecoratorPhone::show(); cout << "挂饰" <<endl; } }; class DecoratorPhoneB:public DecoratorPhone { public: DecoratorPhoneB(Phone *pPhone):DecoratorPhone(pPhone){} virtual void show() { DecoratorPhone::show(); cout << "贴膜" <<endl; } }; int main() { Phone *iphone = new IPhone("iphone4s"); Phone *dpa = new DecoratorPhoneA(iphone); Phone *dpb = new DecoratorPhoneB(dpa); dpb->show(); return 0; }