strategy模式的起因跟template模式是一样的,只不过,它是在template模式上进行了一层改进。我们知道template模式是充分利用了多态的特点,用继承的方式实现了依赖倒转,然而正是继承的强制性约束关系给它带来了不足之处。即,abstract_class的子类中各种原语方法primitive_operation()无法共享,试想,当一个类似于abstract_class的变体abstract_class_2定义了不一样的template_method(),其原语方法想共用前面提到的primitive_operation(),在继承体系中是没法实现的。因为concrete_class跟abstract_class_2没有继承关系。
strategy模式用的是组合,而不是继承,见UML图:
代码:
#ifndef _STRATEGY_H__
#define _STRATEGY_H__
class strategy
{
public:
strategy();
virtual ~strategy();
virtual void algrithm_interface() = 0;
};
class concrete_strategy_A:public strategy
{
public:
concrete_strategy_A();
~concrete_strategy_A();
void algrithm_interface();
};
class concrete_strategy_B:public strategy
{
public:
concrete_strategy_B();
~concrete_strategy_B();
void algrithm_interface();
};
#endif
//strategy.cpp
#include "strategy.h"
#include <iostream>
using namespace std;
strategy::strategy()
{
}
strategy::~strategy()
{
}
concrete_strategy_A::concrete_strategy_A()
{
}
concrete_strategy_A::~concrete_strategy_A()
{
}
void concrete_strategy_A::algrithm_interface()
{
cout<<"A::ALGRITHM_INTERFACE"<<endl;
}
concrete_strategy_B::concrete_strategy_B()
{
}
concrete_strategy_B::~concrete_strategy_B()
{
}
void concrete_strategy_B::algrithm_interface()
{
cout<<"B::ALGRITHM_INTERFACE"<<endl;
}
#ifndef _CONTEXT_H__
#define _CONTEXT_H__
class strategy;
class context
{
public:
context(strategy *);
~context();
void operation();
private:
strategy *_p_stg;
};
#endif
//context.cpp
#include "strategy.h"
#include "context.h"
#include <iostream>
using namespace std;
context::context(strategy *p_stg)
:_p_stg(p_stg)
{
}
context::~context()
{
if (_p_stg)
delete _p_stg;
}
void context::operation()
{
_p_stg->algrithm_interface();
}
#include "strategy.h"
#include "context.h"
#include <iostream>
using namespace std;
int main(int argc,char **argv)
{
strategy *p_stg = new concrete_strategy_A();
context *p_con = new context(p_stg);
p_con->operation();
if (p_con)
delete p_con;
return 0;
}