策略模式(Strategy Pattern)

摘自:算法

策略模式(Strategy):它定義了一系列的算法,並將每個算法封裝起來,並且使它們還能夠相互替換。策 略模式讓算法的變化不會影響到使用算法的客戶。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)ide

 

 

圖1 策略模式類圖單元測試

 優勢:測試

  一、 簡化了單元測試,由於每一個算法都有本身的類,能夠經過本身的接口單獨測試。
  二、 避免程序中使用多重條件轉移語句,使系統更靈活,並易於擴展。
      三、 遵照大部分GRASP原則和經常使用設計原則,高內聚、低偶合。
this

  缺點:
  一、 由於每一個具體策略類都會產生一個新類,因此會增長系統須要維護的類的數量。
      二、 在基本的策略模式中,選擇所用具體實現的職責由客戶端對象承擔,並轉給策略模式的Context對象。(這自己沒有解除客戶端須要選擇判斷的壓力,而策略 模式與簡單工廠模式結合後,選擇具體實現的職責也能夠由Context來承擔,這就最大化的減輕了客戶端的壓力。spa

代碼:設計

    public abstract class Strategy
    {
        public abstract void strategyInterface();
    }

    public class ConcreteStrategy : Strategy
    {
        public override void strategyInterface()
        {
            Console.Write("ConcreteStrategy strategyInterface");
        } 
    }

    public class Context
    {
        private Strategy strategy = null;
        public Context(Strategy strtegy)
        {
            this.strategy = strategy;
        }
        public void contextInterface()
        {
            this.strategy.strategyInterface();
        }
    }

調用:code

  Context context = new Context(new ConcreteStrategy());
  context.contextInterface();
相關文章
相關標籤/搜索