标签:receiveCall 功能 cout void 升级 Phone PhoneDecorator 手机 public
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
#include <iostream>
using namespace std;
class Phone
{
public:
virtual void receiveCall() {};
};
class SimplePhone :public Phone
{
public:
virtual void receiveCall() {
cout << "发出声音!" << endl;
}
};
class PhoneDecorator :public Phone {
protected:
Phone* phone;
public:
PhoneDecorator(Phone* p)
{
phone = p;
}
virtual void receiveCall()
{
phone->receiveCall();
}
};
class JarPhone :public PhoneDecorator {
public:
JarPhone(Phone* p) :PhoneDecorator(p) {}
void receiveCall()
{
phone->receiveCall();
cout << "会震动!" << endl;
}
};
class ComplexPhone :public PhoneDecorator {
public:
ComplexPhone(Phone* p) :PhoneDecorator(p) {}
void receiveCall()
{
phone->receiveCall();
cout << "会发光!" << endl;
}
};
int main()
{
Phone* p1 = new SimplePhone();
p1->receiveCall();
cout << "Jarphone" << endl;
Phone* p2 = new JarPhone(p1);
p2->receiveCall();
cout << "ComplexPhone" << endl;
Phone* p3 = new ComplexPhone(p2);
p3->receiveCall();
return 0;
}
标签:receiveCall,
功能,
cout,
void,
升级,
Phone,
PhoneDecorator,
手机,
public
From: https://www.cnblogs.com/zh-ang-zhang/p/18544540