[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
package test11; public class Client { public static void main(String[]args) { Phone p=new SimplePhone(); p.call(); System.out.println("Simple"); JarPhone p1=new JarPhone(p); p1.shoke(); System.out.println("JarPhone"); ComplexPhone p2=new ComplexPhone(p1); p2.light(); System.out.println("ComplexPhone"); } }
package test11; public class ComplexPhone extends UpgradePhone{ public ComplexPhone(Phone phone){ super(phone); System.out.println("***增加闪光功能***"); } public void light(){ System.out.println("灯光闪烁:咔嚓"); } }
package test11; public class JarPhone extends UpgradePhone{ public JarPhone(Phone phone){ super(phone); System.out.println("***增加振动的功能***"); } public void shoke(){ System.out.println("振动:嗡嗡嗡"); } }
package test11; public interface Phone { public void call(); }
package test11; public class SimplePhone implements Phone{ public SimplePhone(){ System.out.println("手机收到来电"); } public void call(){ System.out.println("主人来电话啦!"); } }
package test11; public class UpgradePhone implements Phone{ private Phone phone; public UpgradePhone(Phone a){ phone=a; } public void call(){ phone.call(); } }
#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; }
标签:java,JarPhone,phone,c++,public,Phone,call,装饰,SimplePhone From: https://www.cnblogs.com/rongzhang/p/16923548.html