设计模式(四):策略模式

一、定义

策略就是算法,封装多种算法,算法之间可以互相替换。类似于,一道数学题有很多的思路和解题方法。

二、实例

推送策略:

 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);

三、优缺点

优:算法的封装,算法的互相替换

缺:客户端需要传递实例,有耦合。当然这可以解决—简单工厂模式、工厂模式。

总归还是比较常用的。

posted @ 2016-01-06 07:47  K战神  阅读(251)  评论(0编辑  收藏  举报