码迷,mamicode.com
首页 > 其他好文 > 详细

装饰者模式

时间:2015-12-31 01:37:33      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

}

创建抽象装饰类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();
    }

}

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

Bluetooth:

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

}

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

    public String Location;

}

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

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

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

}

输出结果

技术分享

 

装饰者模式

标签:

原文地址:http://www.cnblogs.com/gzy1031/p/5090416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!