1、策略模式定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。结构图如下:
2、策略模式剖析:
策略模式是一种定义一系列算法的方法,从概念上看,所有这些算法完成都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。
策略模式的Strategy类层次为Context定义了一系列可供重用的算法或行为。继承有助于抽象出这些算法的公共功能。
3、策略模式的优点是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
当不同的行为堆砌在一个类中时,就很难避免使用条件语句来选择适合的行为。将这些行为封装在一个个独立的Strategy类中,可以在使用这些行为的类中消除条件语句。
4、策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中得到说需要在不同的时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
在基本的策略模式中,选择所用具体实现的职责由客户端对象来承担,并转给策略模式的Context对象。
5、C++实现代码如下:
- #include <iostream>
- using namespace std;
- //策略抽象类
- class Strategy
- {
- public:
- virtual void AlgorithmInterface() {};
- };
- //具体策略类A
- class ConcreteStrategyA: public Strategy
- {
- public:
- void AlgorithmInterface() {
- cout << "算法A的实现" << endl;
- }
- };
- //具体策略类B
- class ConcreteStrategyB: public Strategy
- {
- public:
- void AlgorithmInterface() {
- cout << "算法B的实现" << endl;
- }
- };
- //具体策略类C
- class ConcreteStrategyC: public Strategy
- {
- public:
- void AlgorithmInterface(){
- cout << "算法C的实现" << endl;
- }
- };
- //上下文类
- class Context
- {
- private:
- //指向基类的指针
- Strategy & strategy;
- public:
- Context(Strategy & s):strategy(s){};
- void ContextInterface();
- };
- void Context::ContextInterface() {
- strategy.AlgorithmInterface();
- }
- int main()
- {
- ConcreteStrategyA a;
- ConcreteStrategyB b;
- ConcreteStrategyC c;
- Context contextA(a);
- contextA.ContextInterface();
- Context contextB(b);
- contextB.ContextInterface();
- Context contextC(c);
- contextC.ContextInterface();
- return 0;
- }