2021.10.17 装饰模式c++
一、今日学习内容
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
#include <iostream> #include <string> #include <list> using namespace std; class Phone { public: Phone() {} virtual ~Phone() {} virtual void ShowDecorate() {} }; //具体的手机类 class NokiaPhone : public Phone { private: string m_name; public: NokiaPhone(string name) : m_name(name) {} ~NokiaPhone() {} void ShowDecorate() { cout <<"--------------" <<m_name << "------------------" << endl; } }; //装饰类 class DecoratorPhone : public Phone { private: Phone* m_phone; //要装饰的手机 public: DecoratorPhone(Phone* phone) : m_phone(phone) {} virtual void ShowDecorate() { m_phone->ShowDecorate(); } }; //具体的装饰类 class DecoratorPhoneA : public DecoratorPhone { public: DecoratorPhoneA(Phone* phone) : DecoratorPhone(phone) {} void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); } private: void AddDecorate() { cout << "声音提示" << endl; } //增加的装饰 }; //具体的装饰类 class DecoratorPhoneB : public DecoratorPhone { public: DecoratorPhoneB(Phone* phone) : DecoratorPhone(phone) {} void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); } private: void AddDecorate() { cout << "震动提示" << endl; } //增加的装饰 }; //具体的装饰类 class DecoratorPhoneC : public DecoratorPhone { public: DecoratorPhoneC(Phone* phone) : DecoratorPhone(phone) {} void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); } private: void AddDecorate() { cout << "灯光闪烁提示" << endl; } //增加的装饰 }; int main() { Phone* iphone = new NokiaPhone("SimplePhone"); Phone* dpa = new DecoratorPhoneA(iphone); dpa->ShowDecorate(); Phone* phone = new NokiaPhone("JarPhone"); Phone* dpA = new DecoratorPhoneA(phone); Phone* dpb = new DecoratorPhoneB(dpA); dpb->ShowDecorate(); Phone* cphone = new NokiaPhone("ComplexPhone"); Phone* d = new DecoratorPhoneA(cphone); Phone* dpB = new DecoratorPhoneB(d); Phone* dpC = new DecoratorPhoneC(dpB); dpC->ShowDecorate(); delete dpa; delete iphone; delete dpA; delete dpb; delete phone; delete d; delete dpB; delete dpC; delete cphone; }