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

jopen 8年前

一、定义

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

二、实例

推送策略:

 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