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