设计模式学习笔记(十八)——Strategy策略模式

设计模式学习笔记(十八)——Strategy策略模式

       这段时间在项目中接触到了Strategy策略模式,所以就学习了一下,做一个总结。

       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所示例化的对象就可以。

 

       Strategy模式的要点:

1Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行切换。所谓封装算法,支持算法的变化。

2Strategy模式提供了用条件判断语句以外的另一中选择,消除条件判断语句,就是在解耦合。含有许多条件判断语句的代码通常都需要Strategy模式。

3Strategy模式已算法为中心,可以和Factory Method联合使用,在工厂中使用配制文件对变化的点进行动态的配置。这样就使变化放到了运行时。

4、与Template Method相比,Strategy模式的中心跟集中在方法的封装上

 
《设计模式学习笔记(十八)——Strategy策略模式》  

点赞