C#設計模式之裝飾器模式實例詳解
最近踢了場球,9人制比賽,上半場我們采用防守陣型效果不佳,下半場采用進攻陣型取得了比賽的主動。我們上下半場所采取的策略,似乎可以用"裝飾器"模式實現(xiàn)一遍。
首先肯定是抽象基類。
public abstract class OurStrategy { public abstract void Play(string msg); }
通常,在上半場,我們一般都使用防守陣型。
public class OurDefaultStategy : OurStrategy { public override void Play(string msg) { Console.WriteLine("上半場4-1-2-1防守陣型"); } }
下半場,會根據(jù)上半場的態(tài)勢而調整陣型。也就是需要實現(xiàn)OurStrategy這個抽象類。不過,先不急,我們還得先抽象出一個實現(xiàn)OurStrategy這個抽象類、充當裝飾器的一個抽象類。
public abstract class OurDecorator : OurStrategy { private OurStrategy _ourStrategy; public OurDecorator(OurStrategy ourStrategy) { this._ourStrategy = ourStrategy; } public override void Play(string msg) { if (_ourStrategy != null) { _ourStrategy.Play(msg); } } }
以上,這個充當裝飾器的抽象類,接收某個實現(xiàn)OurStrategy抽象基類的子類實例,并執(zhí)行OurStrategy抽象基類的方法Play。
接下來,實現(xiàn)OurDecorator這個充當裝飾器的類。
public class AttackStategy : OurDecorator { public AttackStategy(OurStrategy ourStrategy) : base(ourStrategy) { } public override void Play(string msg) { base.Play(msg); Console.WriteLine("下半場3-1-3-1進攻陣型"); } }
以上,當然還可以寫出很多OurDecorator的派生類。
客戶端這樣調用:
class Program { static void Main(string[] args) { OurDecorator ourDecorator = new AttackStategy(new OurDefaultStategy()); ourDecorator.Play("haha"); Console.ReadKey(); } }
以上,
通過new AttackStategy(new OurDefaultStategy())把new OurDefaultStategy()實例賦值給類充當裝飾墻的抽象基類OurDecorator的_ourStrategy字段。
當執(zhí)行ourDecorator.Play("haha")方法,首先來到AttackStategy的Play方法,執(zhí)行base.Play(msg),這里的base就是AttackStategy的抽象父類OurDecorator,再執(zhí)行OurDecorator的Play方法,由于已經給OurDecorator的_ourStrategy字段賦值,_ourStrategy字段存儲的是OurDefaultStategy實例,所以,base.Play(msg)最終執(zhí)行的是OurDefaultStategy的Play方法,即把"上半場4-1-2-1防守陣型"顯示出來。
最后執(zhí)行AttackStategy的Play方法中的Console.WriteLine("下半場3-1-3-1進攻陣型")部分,把"下半場3-1-3-1進攻陣型"顯示出來。
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
C#獲取Excel文件所有文本數(shù)據(jù)內容的示例代碼
獲取上傳的?EXCEL?文件的所有文本信息并存儲到數(shù)據(jù)庫里,可以進一步實現(xiàn)對文件內容資料關鍵字查詢的全文檢索,有助于我們定位相關文檔,本文詳細介紹了C#獲取Excel文件所有文本數(shù)據(jù)內容實現(xiàn)步驟和代碼,需要的朋友可以參考下2024-07-07