装饰者模式

要求:

 

程序的UML图以及代码:

(1)创建抽象组件类MobilePhone。

 public abstract class MobilePhone
 {
     public String phoneName;
     public abstract void SendMessage();
     public abstract void Call();
 }

 

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

MiPhone:

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.");
    }

}

 

iPhone:

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.");
    }

}

 

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

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();
    }

}

 

(4)创建具体装饰类Bluetooth、GPS、Camera。

Bluetooth:

public class Bluetooth extends Decorator
{
    public Bluetooth(MobilePhone mobilePhone) 
    {
        super(mobilePhone);
    }
    
    public void Connect()
    {
        System.out.println( phoneName+"增加蓝牙功能。" );
    }

}

GPS:

public class GPS extends Decorator
{
    public GPS(MobilePhone mobilePhone)
    {
        super(mobilePhone);
    }

    public String Location;

}

Camera:

public class Camera extends Decorator
{
    public Camera(MobilePhone mobilePhone)
    {
        super(mobilePhone);
    }

    public void VideoCall()
    {
        System.out.println(phoneName+"增加视频电话功能。");
    }
}

 

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

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();
    }

}

 

输出结果:

 

posted @ 2015-12-30 23:18  your_stone  阅读(124)  评论(0)    收藏  举报