2. 類應設計的對擴展開放,對修改關閉。
實例:
// 裝飾者模式抽象類 public abstract class BaseDecorator { protected ReturnInfo returnInfo = new ReturnInfo() { Code = 1, IsSuccess = false }; public BaseDecorator decorator = null; //裝飾者模式必須要傳入上一個裝飾者對象,如果沒有則傳null public BaseDecorator(BaseDecorator _decorator) { decorator = _decorator; } // 執行方法 public abstract ReturnInfo Run(string orderId,string supplierId,string supOrderId); // 返回結果 protected ReturnInfo GetResult() { returnInfo.Code = 0; returnInfo.IsSuccess = true; returnInfo.Message = "操作成功"; return returnInfo; } }public class DecoratorA:BaseDecorator { public DecoratorA(BaseDecorator decorator) : base(decorator) { } public override Model.ReturnInfo Run(string orderId, string supplierId, string supOrderId) { //具體執行的方法 //判斷是否還有裝飾者需要執行 if (decorator!=null) { return decorator.Run(orderId, supplierId,supOrderId); } else { return GetResult(); } } }public class DecoratorB:BaseDecorator { public DecoratorB(BaseDecorator decorator) : base(decorator) { } public override Model.ReturnInfo Run(string orderId, string supplierId, string supOrderId) { //具體執行的方法 //判斷是否還有裝飾者需要執行 if (decorator!=null) { return decorator.Run(orderId, supplierId,supOrderId); } else { return GetResult(); } } }public class Test { BaseDecorator decorator = new DecoratorA(null); decorator = new DecoratorB(decorator); //程序是從下往上執行的 return decorator.Run(orderId,supplierId,supOrderId); }