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