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

装饰模式

时间:2015-12-31 00:07:53      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

这次学习了装饰模式,装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

技术分享

代码展示

    Bluetooth:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰模式作业
{

public class Bluetooth:Function
{
public Bluetooth(MobilePhone mobilephone)
: base(mobilephone)
{

}


public void Connect()
{
Console.WriteLine("蓝牙正在连接");
}
}
}

 

 

       Camera:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰模式作业
{
public class Camera:Function
{
public Camera(MobilePhone mobilephone)
: base(mobilephone)
{

}

public override void Call()
{
Console.WriteLine("通信功能升级为带有视频");
}
}
}

 

         Function:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰模式作业
{
public class Function:MobilePhone
{
private MobilePhone _mobilephone;

public Function(MobilePhone mobilephone)
{
_mobilephone = mobilephone;
}

public override void SendMessage()
{
_mobilephone.SendMessage();
}

public override void Call()
{
_mobilephone.Call();
}

}
}

 

     GPS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰模式作业
{

public class GPS:Function
{
public string Localtion { get; set; }

public GPS(MobilePhone mobilephone)
: base(mobilephone)
{

}
}
}

 

 

     MobilePhone

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰模式作业
{
public abstract class MobilePhone
{
public abstract void SendMessage();
public abstract void Call();
}
}

 

          Phone

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰模式作业
{
public class Phone:MobilePhone
{
public Phone()
{ }

public override void SendMessage()
{
Console.WriteLine("发送短信");
}

public override void Call()
{
Console.WriteLine("普通通信");
}
}

public class MiPhone : MobilePhone
{
public MiPhone()
{ }

public override void SendMessage()
{
Console.WriteLine("发送短信");
}

public override void Call()
{
Console.WriteLine("普通通信");
}


}
}

 

 

      Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰模式作业
{
class Program
{
static void Main(string[] args)
{
MobilePhone mobilephone = new Phone();
mobilephone.SendMessage();
mobilephone.Call();

Bluetooth bluetooth = new Bluetooth(mobilephone);
bluetooth.Connect();

GPS gps = new GPS(bluetooth);
gps.Localtion = "678,898,90,56";

Camera camera = new Camera(gps);

camera.Call();

Console.ReadLine();

}
}
}

 

 

             

装饰模式

标签:

原文地址:http://www.cnblogs.com/glaaa/p/5090381.html

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