設計模式(四):策略模式

jopen 8年前發布 | 13K 次閱讀 策略模式

一、定義

策略就是算法,封裝多種算法,算法之間可以互相替換。類似于,一道數學題有很多的思路和解題方法。

二、實例

推送策略:

 public interface  IPushStrategy
    {
        bool Push();
    }

    public class QQPush : IPushStrategy
    {
        public bool Push()
        {
            Console.WriteLine("QQ推送.");
            return true;
        }
    }

    public class EmailPush : IPushStrategy
    {
        public bool Push()
        {
            Console.WriteLine("Email推送.");
            return true;
        }
    }

推送服務:

 public class PushService
    {
        IPushStrategy push;
        public PushService(IPushStrategy _push)
        {
            push = _push;
            Console.WriteLine("啟動:推送服務.");
            push.Push();
        }

    }

客戶端:

//策略模式
Strategy.IPushStrategy emailpush = new Strategy.EmailPush();
Strategy.PushService ps = new Strategy.PushService(emailpush);

三、優缺點

優:算法的封裝,算法的互相替換

缺:客戶端需要傳遞實例,有耦合。當然這可以解決—簡單工廠模式、工廠模式。

總歸還是比較常用的。

來自: http://www.cnblogs.com/sunchong/p/5104307.html

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!