装饰模式——C++实现
问题描述:
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图:
代码:
#include <iostream> #include <string> #include <list> using namespace std; //抽象构建——Phone类 class Phone { public: Phone() {} virtual ~Phone() {} virtual void call() {} }; //具体构建——SimplePhone class SimplePhone : public Phone { private: string name; public: SimplePhone(string name) : name(name) {} ~SimplePhone() {} void call() { cout <<"--------------" <<name << "------------------" << endl; cout<<"响铃:主人来电话啦!"<<endl; } }; //抽象装饰类——UpgradePhone class UpgradePhone : public Phone { private: Phone* phone; public: UpgradePhone(Phone* phone) : phone(phone) {} virtual void call() { phone->call(); } }; //具体装饰类——JarPhone class JarPhone : public UpgradePhone { public: JarPhone(Phone* phone) : UpgradePhone(phone) {} void call() { UpgradePhone::call(); shoke(); } private: void shoke() { cout << "振动:嗡嗡嗡" << endl; } }; //具体装饰类—— ComplexPhone class ComplexPhone : public UpgradePhone { public: ComplexPhone(Phone* phone) : UpgradePhone(phone) {} void call() { UpgradePhone::call(); light(); } private: void light() { cout << "闪光:咔嚓" << endl; } }; int main() { Phone* phone = new SimplePhone("SimplePhone"); phone->call(); Phone* jphone = new SimplePhone("JarPhone"); Phone* ph1 = new JarPhone(jphone); ph1->call(); Phone* cphone = new SimplePhone("ComplexPhone"); Phone* ph2 = new JarPhone(cphone); Phone* ph3 = new ComplexPhone(ph2); ph3->call(); delete phone; delete jphone; delete ph1; delete ph2; delete ph3; delete cphone; }
运行截图: