2021/11/8

手机功能的升级

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

二、类图

 

 

 

 

 1 package tutorial11;
 2 
 3 public class Client {
 4 
 5     public static void main(String[] args) {
 6         // TODO 自动生成的方法存根
 7 
 8           Phone p1 = new SimplePhone();
 9           System.out.println("生产简单手机");
10           p1.serviceCall();
11           
12           System.out.println("***********************");
13           Phone p2 = new JarPhone(p1);
14           System.out.println("升级手机为JarPhone");
15           p2.serviceCall();
16           System.out.println("***********************");
17           Phone p3 = new ComplexPhone(p2);
18           System.out.println("升级手机为ComplexPhone");
19           p3.serviceCall();
20     }
21 
22 }

  

package tutorial11;
2 
3 public abstract class Phone {
4 
5     public void serviceCall() {
6         
7     }
8 }

  

1 package tutorial11;
2 
3 public class SimplePhone extends Phone {
4 
5     public void serviceCall() {
6         System.out.println("SimplePhone:发出声音提醒主人电话来了");
7     }
8 }

SimplePhone

  

1 package tutorial11;
 2 
 3 public class PhoneDecoration extends Phone {
 4 
 5     private Phone phone=null;
 6     public PhoneDecoration(Phone phone) {
 7           if(phone!=null){
 8                  this.phone = phone;
 9              }else{
10                  this.phone = new SimplePhone();
11              }
12     }
13     @Override
14     public void serviceCall() {
15         phone.serviceCall();
16     }
17 }

PhoneDecoration

  

posted @ 2021-11-08 17:17  小强哥in  阅读(73)  评论(0编辑  收藏  举报