說(shuo)說(shuo)設計模式~裝飾器模式(Decorator)
裝(zhuang)飾器模式,也叫又(you)叫裝(zhuang)飾者模式,顧名思(si)義(yi),將一個(ge)對象(xiang)進行包裹,包裝(zhuang),讓它變成(cheng)一個(ge)比較滿意的(de)對象(xiang),這(zhe)種(zhong)(zhong)模式在(zai)我們平(ping)時項目(mu)開發中,經常會用到,事實上,它是(shi)處理(li)問題的(de)一種(zhong)(zhong)技巧,也很(hen)好(hao)的(de)擴展了程序,讓程序代碼不(bu)那么死板!
何時能用到它?
1. 需要擴展一(yi)(yi)個類的(de)功能(neng),或給一(yi)(yi)個類添加附加職責。
2. 需要動態的給(gei)一個對(dui)象添加功(gong)能(neng),這些功(gong)能(neng)可(ke)以再動態的撤銷。
3. 需(xu)要(yao)增加由一(yi)些基本功(gong)能的(de)(de)(de)排列組合而產(chan)生(sheng)的(de)(de)(de)非常大量的(de)(de)(de)功(gong)能,從而使繼承關系變的(de)(de)(de)不(bu)現實(shi)。
4. 當不能采用生成子類的方法進行擴充(chong)時(shi)。
其中我們認為第四種使用是比較巧妙的,這一講中,主要是以第四講為例來說明的
裝飾器模式的結構圖
裝飾器模式實現說明
IAction:裝(zhuang)飾器標準接口(kou),所有裝(zhuang)飾功能都(dou)要(yao)實(shi)現它
DelegateAction:裝飾類,用來(lai)實現IAction插口的功能,并對外部提供另一種表現形式
StandardAction:標(biao)準實現類,用(yong)來(lai)實現IAction插口(kou)(kou)的(de)功能,對外展示也是以IAction接口(kou)(kou)為準的(de)
Implement:對(dui)外公(gong)開的(de)調用類,它向外界公(gong)開兩種(zhong)接(jie)(jie)口方(fang)法,一是IAction接(jie)(jie)口標準,一是Action<int>委托標準
裝飾器模式的C#實現
#region 裝飾模式 public interface IAction { void Print(int a); } sealed class DelegateAction : IAction { Action<int> _action; public DelegateAction(Action<int> action) { _action = action; } public void Print(int a) { _action(a); } } public class standardAction : IAction { public void Print(int a) { Console.WriteLine("標準實現裝(zhuang)飾(shi)器(qi)" + a); } } public class Implement { public void Run(IAction action) { action.Print(10); } public void Run(Action<int> action) { new DelegateAction(action).Print(10); } } #endregion
調用的代碼
Implement implement = new Implement(); implement.Run((a) => Console.WriteLine(a));//委托Action<int>調用法 implement.Run(new standardAction());//IAction對(dui)象調用法