手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图
java
package rjsj.no11; public class Client { public static void main(String[] args) { CellPhone phone1 = new SimplePhone(); CellPhone phone2 = new JarPhone(phone1); CellPhone phone3 = new ComplexPhone(phone2); phone1.receiveCall(); System.out.println("********************************************************************************"); phone2.receiveCall(); System.out.println("********************************************************************************"); phone3.receiveCall(); } }
package rjsj.no11; public class ComplexPhone extends PhoneDecorator{ public ComplexPhone(CellPhone cellPhone) { super(cellPhone); } @Override public void receiveCall() { super.receiveCall(); System.out.println("闪光灯闪烁"); } }
package rjsj.no11; public class JarPhone extends PhoneDecorator{ public JarPhone(CellPhone cellPhone) { super(cellPhone); } @Override public void receiveCall() { super.receiveCall(); System.out.println("发出震动"); } }
package rjsj.no11; public class PhoneDecorator extends CellPhone{ private CellPhone cellPhone = null; public PhoneDecorator(CellPhone cellPhone){ if (cellPhone != null){ this.cellPhone = cellPhone; } else { this.cellPhone = new SimplePhone(); } } @Override public void receiveCall() { cellPhone.receiveCall(); } }
package rjsj.no11; public class SimplePhone extends CellPhone{ @Override public void receiveCall() { System.out.println("发出声音"); } }
package rjsj.no11; abstract class CellPhone { public abstract void receiveCall(); }
C++
#include <iostream> using namespace std; class Phone{ public: virtual void receiveCall(){}; }; class PhoneDecorator:public Phone { protected: Phone *phone; public: PhoneDecorator(Phone *p){ phone=p; } virtual void receiveCall(){ phone->receiveCall(); } }; class SimplePhone:public Phone{ public: virtual void receiveCall(){ cout<<"发出声音"<<endl; } }; 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,cellPhone,CellPhone,void,模式,public,class,装饰 From: https://www.cnblogs.com/libin159/p/16861479.html