装饰模式(二)
#include<iostream> #include<string> using namespace std; class Phone{ public:virtual void receiveCall()=0; }; class SimplePhone :public Phone{ public:void receiveCall(){ cout << "接受来电,电话响了" << endl; } }; class PhoneDecorator :public Phone{ private:Phone *pho; public:PhoneDecorator(Phone *p){ if (p != NULL){ pho = p; } else{ pho = new SimplePhone(); } } void receiveCall(){ pho->receiveCall(); } }; class JarPhone:public PhoneDecorator{ private:Phone *p; public: JarPhone(Phone *p):PhoneDecorator(p) { // TODO Auto-generated constructor stub this->p = p; } void receiveCall(){ p->receiveCall(); cout<<"接受来电,手机震动"<<endl; } }; class ComplexPhone :public PhoneDecorator{ private:Phone *p; public: ComplexPhone(Phone *p) :PhoneDecorator(p) { // TODO Auto-generated constructor stub this->p = p; } void receiveCall(){ p->receiveCall(); cout << "接受来电,灯光闪烁" << endl; } }; int main(){ Phone *p = new SimplePhone(); p->receiveCall(); cout<<"Simple"<<endl; Phone *p1 = new JarPhone(p); p1->receiveCall(); cout<<"JarPhone"<<endl; Phone *p2 = new ComplexPhone(p1); p2->receiveCall(); cout<<"ComplexPhone"<<endl; }