天天看点

策略模式

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

(原文:The Strategy Pattern defines a family of

algorithms,encapsulates each one,and makes them interchangeable. Strategy lets

the algorithm vary independently from clients that use it.)

Context(应用场景):

1、需要使用ConcreteStrategy提供的算法。

2、 内部维护一个Strategy的实例。

3、 负责动态设置运行时Strategy具体的实现算法。

4、负责跟Strategy之间的交互和数据传递。

Strategy(抽象策略类):

1、

定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,Context使用这个接口调用不同的算法,一般使用接口或抽象类实现。

ConcreteStrategy(具体策略类):

2、 实现了Strategy定义的接口,提供具体的算法实现。

策略模式

策略模式与简单工厂模式组合:

策略模式

同样地,策略模式可以与工厂方法模式或抽象工厂模式组合。