《设计模式之禅》学习之策略模式

来源:互联网 发布:网络歌曲大全2017 编辑:程序博客网 时间:2024/06/09 21:17

         1.策略模式(Strategy)的概念:它定义了算法家族,分别封装起来,让他们之间可以相互替换,次模式让算法的变化,不会影响到用算法的客户。

         2.场景描述:刘备要到江东娶老婆了,走之前诸葛亮给赵云(伴郎)三个锦囊妙计,说是按天机拆开解决棘手问题,嘿,还别说,真是解决了大问题,搞到最后是周瑜陪了夫人又折兵呀,那咱们先看看这个场景是什么样子的。 先说这个场景中的要素:三个妙计,一个锦囊,一个赵云,妙计是小亮同志给的,妙计是放置在锦囊里,俗称就是锦囊妙计嘛,那赵云就是一个干活的人,从锦囊中取出妙计,执行,然后获胜。

          3.类图表现:

          4.C#代码实现:

               IStrategy接口代码:

namespace Strategy{    public interface IStrategy    {         void operate();    }}

实现该借口的三个策略,代码依次为:

 class BackDoor : IStrategy    {        #region IStrategy Members        public void  operate()        {            Console.WriteLine("找乔国老帮忙,让吴国太给孙权施加压力");        }        #endregion   }    class GivenGreenLigth :IStrategy    {        #region IStrategy Members        public void operate()        {            Console.WriteLine("找吴国太开绿灯,放行!");        }        #endregion    }      class BlockEnemy :IStrategy    {        #region IStrategy Members        public void operate()        {            Console.WriteLine("孙夫人断后,阻挡追兵");        }        #endregion    }


存放锦囊的类:

 class Context    {        private IStrategy strategy;        public Context(IStrategy strategy)        {            this.strategy = strategy;        }        public void operate()        {            this.strategy.operate();        }    }

赵云的运作类:

 

class ZhaoYun    {        static void Main(string[] args)        {            Context context;            //刚刚到吴国            Console.WriteLine("------------ 刚到吴国的时候拆第一个-----------------");            context = new Context(new BackDoor());//得到第一个锦囊            context.operate();//拆开执行            Console.WriteLine(); Console.WriteLine();            //刚刚到吴国            Console.WriteLine("------------ 乐不思蜀的时候拆第二个-----------------");            context = new Context(new GivenGreenLigth());//得到第一个锦囊            context.operate();//拆开执行            Console.WriteLine(); Console.WriteLine();            //刚刚到吴国            Console.WriteLine("------------ 吴国追兵的时候拆第一个-----------------");            context = new Context(new BlockEnemy());//得到第一个锦囊            context.operate();//拆开执行            Console.WriteLine(); Console.WriteLine();          Console.ReadKey();        }    }

结论:
这就是策略模式,高内聚低耦合的特点也表现出来了,还有一个就是扩展性,也就是 OCP原则,策略类可以继续增加下去,只要添加类,实现IStrategy接口即可,

这个不多说了,自己领会吧。

 

 

原创粉丝点击