定义
即在不改变类本身,动态地扩展对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。包装对象和原对象拥有相似的接口方法(功能)。
举例
类图
代码
public class OrderInfo { /// <summary> /// 下单时间 /// </summary> public DateTime CreateTime{get;set;} /// <summary> /// 等级 /// </summary> public int Level{get;set;} } public abstract class OrderManager { public abstract void Summit(OrderInfo order); public abstract void CancelOrder(OrderInfo order); } public class SimpleOrderManager : OrderManager { public override void Summit(OrderInfo order) { //TODO summit the order Console.WriteLine("Summit the order"); } public override void CancelOrder(OrderInfo order) { //TODO cancel the order Console.WriteLine("cancel the order"); } } /// <summary> /// /// </summary> public class OrderManagerDecorator : OrderManager { private OrderManager orderManager = null; public OrderManagerDecorator(OrderManager orderManager) { this.orderManager = orderManager; } public override void Summit(OrderInfo order) { orderManager.Summit(order); } public override void CancelOrder(OrderInfo order) { orderManager.CancelOrder(order); } } public class ForeignOrderManager : OrderManagerDecorator { public ForeignOrderManager(OrderManager orderManager):base(orderManager) { } public override void Summit(OrderInfo order) { if (ValidateOrder(order)) { base.Summit(order); } else { throw new Exception("the level of the order is disable"); } } public bool ValidateOrder(OrderInfo order) { //TODO validate the order bool result = order.Level > 2; return result; } public override void CancelOrder(OrderInfo order) { base.CancelOrder(order); } } public class SuperOrderManager : OrderManagerDecorator { public SuperOrderManager(OrderManager orderManager) : base(orderManager) { } public override void Summit(OrderInfo order) { base.Summit(order); } public override void CancelOrder(OrderInfo order) { base.CancelOrder(order); } private bool CheckOrder(OrderInfo order) { if (order.CreateTime.AddDays(3) < DateTime.Now) { return false; } else { return true; } } }
总结
曾经以为装饰模式和组合模式很像!只是因为他们他们都包含需要包装的对象。而后来想想,才知道他们本质上差别很大:组合模式在于组合,是多个对象组合成合成的对象,合成对象可以去触发控制其包含的对象。装饰者模式则是对类本身功能的扩展,从代码上看,他是包含单个包装对象。
在编程中非常经典的使用就是Stream类型对象的构造了。主要包括FileSteam,BufferdStream等。
最后在画一幅图说明装饰模式调用的样式------实现装饰功能本身的扩展