首页 > 其他 > 详细

装饰者模式(例子)

时间:2016-01-01 14:45:35      阅读:187      评论:0      收藏:0      [点我收藏+]

技术分享

根据上述要求来用建造者模式设计程序。

 

以下是本程序的UML图以及代码:

技术分享

1、创建抽象组件类MobilePhone。

1 public abstract class MobilePhone
2 {
3     public String phoneName;
4     public abstract void SendMessage();
5     public abstract void Call();
6 }

2、分别创建具体组件小米和苹果手机类,继承自MobilePhone。

技术分享 MiPhone
技术分享 iPhone

3、创建抽象装饰类Decorator,包含一个MobilePhone类型的私有变量。

技术分享
 1 public class Decorator extends MobilePhone{
 2 
 3     private MobilePhone _mobilePhone;
 4     
 5     public Decorator(MobilePhone mobilePhone){
 6         _mobilePhone=mobilePhone;
 7         phoneName=mobilePhone.phoneName;
 8     }
 9     @Override
10     public void SendMessage() {
11         // TODO Auto-generated method stub
12         _mobilePhone.SendMessage();
13     }
14 
15     @Override
16     public void Call() {
17         // TODO Auto-generated method stub
18         _mobilePhone.Call();
19     }
20 
21 }
技术分享

4、分别创建具体装饰类Bluetooth、GPS、Camera。

技术分享 Bluetooth
技术分享 GPS
技术分享 Camera

5、书写主函数Main来分别创建小米手机和苹果手机,并且分别加上蓝牙功能、GPS功能和视频通话功能。

技术分享
 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         MiPhone miPhone=new MiPhone();
 6         iPhone iphone=new iPhone();
 7         
 8         Bluetooth miBluetooth=new Bluetooth(miPhone);
 9         miBluetooth.Connect();
10         GPS miGPS=new GPS(miPhone);
11         miGPS.Location="MiPhone的定位成功";
12         System.out.println(miGPS.Location);
13         Camera miCamera=new Camera(miPhone);
14         miCamera.VideoCall();
15         
16         Bluetooth iBluetooth=new Bluetooth(iphone);
17         iBluetooth.Connect();
18         GPS iGPS=new GPS(iphone);
19         miGPS.Location="iPhone的定位成功";
20         System.out.println(miGPS.Location);
21         Camera iCamera=new Camera(iphone);
22         iCamera.VideoCall();
23     }
24 
25 }
技术分享

输出结果看是否符合要求:

 技术分享

装饰者模式(例子)

原文:http://www.cnblogs.com/leaderchen/p/5093221.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!