程序的UML图:
程序的代码:
public abstract class MobilePhone { public String phoneName; public abstract void SendMessage(); public abstract void Call(); }//创建抽象组件类MobilePhone
public class MiPhone extends MobilePhone { public MiPhone() { phoneName="MiPhone"; } public void SendMessage() { System.out.println( phoneName+"‘s SendMessage." ); } public void Call() { System.out.println( phoneName+"‘s Call."); } }//创建具体组件小米和苹果手机类,继承自MobilePhone。 MiPhone
public class iPhone extends MobilePhone { public iPhone() { phoneName="iPhone"; } public void SendMessage() { System.out.println( phoneName+"‘s SendMessage." ); } public void Call() { System.out.println( phoneName+"‘s Call."); } }//iPhone
public class Decorator extends MobilePhone { private MobilePhone _mobilePhone; public Decorator(MobilePhone mobilePhone) { _mobilePhone=mobilePhone; phoneName=mobilePhone.phoneName; } public void SendMessage() { _mobilePhone.SendMessage(); } public void Call() { _mobilePhone.Call(); } }//创建抽象装饰类Decorator,包含一个MobilePhone类型的私有变量
public class Bluetooth extends Decorator { public Bluetooth(MobilePhone mobilePhone) { super(mobilePhone); } public void Connect() { System.out.println( phoneName+"增加蓝牙功能。" ); } }//创建Bluetooth
public class GPS extends Decorator { public GPS(MobilePhone mobilePhone) { super(mobilePhone); } public String Location; }//创建GPS
public class Camera extends Decorator { public Camera(MobilePhone mobilePhone) { super(mobilePhone); } public void VideoCall() { System.out.println(phoneName+"增加视频电话功能。"); } }//创建Camera
public class Main { public static void main(String[] args) { MiPhone miPhone=new MiPhone(); iPhone iphone=new iPhone(); Bluetooth miBluetooth=new Bluetooth(miPhone); miBluetooth.Connect(); GPS miGPS=new GPS(miPhone); miGPS.Location="MiPhone的定位成功"; System.out.println(miGPS.Location); Camera miCamera=new Camera(miPhone); miCamera.VideoCall(); Bluetooth iBluetooth=new Bluetooth(iphone); iBluetooth.Connect(); GPS iGPS=new GPS(iphone); miGPS.Location="iPhone的定位成功"; System.out.println(miGPS.Location); Camera iCamera=new Camera(iphone); iCamera.VideoCall(); } }//主函数Main来分别创建小米手机和苹果手机,并且分别加上蓝牙功能、GPS功能和视频通话功能
输出结果:
原文:http://www.cnblogs.com/fanghaibin/p/5090433.html