每日博客
装饰模式
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外
,还有灯光闪烁提示。
1 public class Changer implements Phone{ 2 private Phone phone; 3 public Changer(Phone p) { 4 this.phone=p; 5 } 6 public void voice() { 7 phone.voice(); 8 } 9 } 10 public class ComplexPhone extends Changer{ 11 public ComplexPhone(Phone p) { 12 super(p); 13 System.out.println("ComplexPhone"); 14 } 15 public void zhendong() { 16 System.out.println("会震动!"); 17 } 18 public void dengguang() { 19 System.out.println("会发光!"); 20 } 21 } 22 public class JarPhone extends Changer{ 23 public JarPhone(Phone p) { 24 super(p); 25 System.out.println("Jarphone"); 26 } 27 public void zhendong() { 28 System.out.println("会震动!"); 29 } 30 } 31 public interface Phone { 32 public void voice(); 33 } 34 public class SimplePhone implements Phone{ 35 public void voice() { 36 System.out.println("发出声音!"); 37 } 38 } 39 public class Client { 40 public static void main(String[] args) { 41 Phone phone; 42 phone=new SimplePhone(); 43 phone.voice(); 44 JarPhone jarphone=new JarPhone(phone); 45 jarphone.voice(); 46 jarphone.zhendong(); 47 ComplexPhone complexphone = new ComplexPhone(phone); 48 complexphone.zhendong(); 49 complexphone.dengguang(); 50 } 51 } 52 53 C++ 54 #include <iostream> 55 using namespace std; 56 class Phone 57 { 58 public: 59 virtual void receiveCall(){}; 60 }; 61 class SimplePhone:public Phone 62 { 63 public: 64 virtual void receiveCall(){ 65 cout<<"发出声音!"<<endl; 66 } 67 }; 68 class PhoneDecorator:public Phone { 69 protected: 70 Phone *phone; 71 public: 72 PhoneDecorator(Phone *p) 73 { 74 phone=p; 75 } 76 virtual void receiveCall() 77 { 78 phone->receiveCall(); 79 } 80 }; 81 class JarPhone:public PhoneDecorator{ 82 public: 83 JarPhone(Phone *p):PhoneDecorator(p){} 84 void receiveCall() 85 { 86 phone->receiveCall(); 87 cout<<"会震动!"<<endl; 88 } 89 }; 90 class ComplexPhone:public PhoneDecorator{ 91 public: 92 ComplexPhone(Phone *p):PhoneDecorator(p){} 93 void receiveCall() 94 { 95 phone->receiveCall(); 96 cout<<"会发光!"<<endl; 97 } 98 }; 99 int main() 100 { 101 Phone *p1=new SimplePhone(); 102 p1->receiveCall(); 103 cout<<"Jarphone"<<endl; 104 Phone *p2=new JarPhone(p1); 105 p2->receiveCall(); 106 cout<<"ComplexPhone"<<endl; 107 Phone *p3=new ComplexPhone(p2); 108 p3->receiveCall(); 109 return 0; 110 }