posts - 124,  comments - 29,  trackbacks - 0

 

       Strategy策略模式是一种对象行为模式。主要是应对:在软件构建过程中,某些对象使用的算法可能多种多样,经常发生变化。如果在对象内部实现这些算法,将会使对象变得异常复杂,甚至会造成性能上的负担。

       GoF设计模式》中说道:定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。该模式使得算法可独立于它们的客户变化。

       Strategy模式的结构图如下:


 

 

 


      
从图中我们不难看出:Strategy模式实际上就是将算法一一封装起来,如图上的ConcreteStrategyAConcreteStrategyBConcreteStrategyC,但是它们都继承于一个接口,这样在Context调用时就可以以多态的方式来实现对于不用算法的调用。

       Strategy模式的实现如下:

       我们现在来看一个场景:我在下班在回家的路上,可以有这几种选择,走路、骑车、坐车。首先,我们需要把算法抽象出来:

       public interface IStrategy

    {

        void OnTheWay();

}

接下来,我们需要实现走路、骑车和坐车几种方式。

public class WalkStrategy : IStrategy

    {

        public void OnTheWay()

        {

            Console.WriteLine("Walk on the road");

        }

    }

 

    public class RideBickStragtegy : IStrategy

    {

        public void OnTheWay()

        {

            Console.WriteLine("Ride the bicycle on the road");

        }

    }

 

    public class CarStragtegy : IStrategy

    {

        public void OnTheWay()

        {

            Console.WriteLine("Drive the car on the road");

        }

}

 

最后再用客户端代码调用封装的算法接口,实现一个走路回家的场景:

class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Arrive to home");

            IStrategy strategy = new WalkStrategy();

            strategy.OnTheWay();

            Console.Read();

        }

}

运行结果如下;

Arrive to home

Walk on the road

如果我们需要实现其他的方法,只需要在Context改变一下IStrategy所示例化的对象就可以。

posted on 2008-06-18 09:38 天书 阅读(155) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2008年6月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

常用链接

留言簿(5)

随笔档案

文章分类

文章档案

好友的Bolg

搜索

  •  

最新评论

阅读排行榜

评论排行榜