码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-01-06 08:03:13      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

一、定义

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

二、实例

技术分享

推送策略:

 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!