1.Decorrator中保存有一个Component,然后ConcoreteComponent中就可以给ConcoreteComponent添加一些职责
2.场景:我们现在用的手机功能很多,我就用Decorator模式实现一下对某个手机的GSP和蓝牙功能扩展
3.代码:
手机:
public abstract class AbstractCellPhone { public abstract string CallNumber(); public abstract string SendMessage(); }
Nokia和Moto的手机:
public class NokiaPhone : AbstractCellPhone { public override string CallNumber() { return "NokiaPhone call sombody"; } public override string SendMessage() { return "NokiaPhone send a message to somebody"; } } public class MotoPhone : AbstractCellPhone { public override string CallNumber() { return "MotoPhone call sombody"; } public override string SendMessage() { return "MotoPhone send a message to somebody"; } }
装饰类:
public abstract class Decorator:AbstractCellPhone { AbstractCellPhone _phone; public Decorator(AbstractCellPhone phone) { _phone = phone; } public override string CallNumber() { return _phone.CallNumber(); } public override string SendMessage() { return _phone.SendMessage(); } }
GSP和蓝牙的职责扩展:
public class DecoratorGPS : Decorator { public DecoratorGPS(AbstractCellPhone phone) : base(phone) { } public override string CallNumber() { return base.CallNumber() + " with GPS"; } public override string SendMessage() { return base.SendMessage() + " with GPS"; } } public class DecoratorBlueTooth : Decorator { public DecoratorBlueTooth(AbstractCellPhone phone) : base(phone) { } public override string CallNumber() { return base.CallNumber() + " with BlueTooth"; } public override string SendMessage() { return base.SendMessage() + " with BlueTooth"; } }
客户端调用:
static void Main(string[] args) { AbstractCellPhone phone = new NokiaPhone(); Console.WriteLine(phone.CallNumber()); Console.WriteLine(phone.SendMessage()); DecoratorGPS gps = new DecoratorGPS(phone); //add GSP Console.WriteLine(gps.CallNumber()); Console.WriteLine(gps.SendMessage()); DecoratorBlueTooth bluetooth = new DecoratorBlueTooth(gps); //add GSP and bluetooth Console.WriteLine(bluetooth.CallNumber()); Console.WriteLine(bluetooth.SendMessage()); Console.Read(); }
参考文章:http://www.cnblogs.com/kid-li/archive/2006/06/26/435966.html