用装饰模式模拟手机功能的升级过程
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。

ComplexPhone
public class ComplexPhone extends PhoneDecorator{
public ComplexPhone(Phone p) {
// TODO Auto-generated constructor stub
super(p);
}
public void receiveCall() {
super.receiveCall();
System.out.println("接受来电,灯光闪烁");
}
}
JarPhone
public class JarPhone extends PhoneDecorator{ public JarPhone(Phone p) { // TODO Auto-generated constructor stub super(p); } public void receiveCall() { super.receiveCall(); System.out.println("接受来电,手机震动"); } }
Phone
public abstract class Phone { public abstract void receiveCall(); }
PhoneDecorator
public class PhoneDecorator extends Phone{ private Phone phone; public PhoneDecorator(Phone p) { // TODO Auto-generated constructor stub if(p!=null) { phone=p; }else { phone=new SimplePhone(); } } @Override public void receiveCall() { // TODO Auto-generated method stub phone.receiveCall(); } }
SimplePhone
public class SimplePhone extends Phone { @Override public void receiveCall() { // TODO Auto-generated method stub System.out.println("接受来电,电话响了"); } }
Client
public class Client { public static void main(String[]args) { Phone p=new SimplePhone(); p.receiveCall(); System.out.println("Simple"); Phone p1=new JarPhone(p); p1.receiveCall(); System.out.println("JarPhone"); Phone p2=new ComplexPhone(p1); p2.receiveCall(); System.out.println("ComplexPhone"); } }

c++代码
#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; }


浙公网安备 33010602011771号