按照自己的理解就是:
一个策略完成的方法有多种,具体的实现类里面包含一个策略虚基类的指针,根据子类实例化的类调用具体方法
strategy.h:
#include <iostream>
using namespace std;
class Strategy
{
public:
Strategy() {};
virtual ~Strategy() {};
virtual void dosomething()=0;
};
class Method1 : public Strategy
{
public:
void dosomething() {
cout << "method1 dosomething" << endl;
}
};
class Method2 : public Strategy
{
public:
void dosomething() {
cout << "method2 dosomething" << endl;
}
};
class Content
{
public:
Content(Strategy* stra) : stra_(stra) {};
~Content() {
if (stra_ != NULL) {
delete stra_;
stra_ = NULL;
}
}
void doAction() {
if (stra_ != NULL)
stra_->dosomething();
}
private:
Strategy* stra_;
};
strategy.cpp:
#include "strategy.h"
int main()
{
Strategy* s1 = new Method1;
Content* con1 = new Content(s1);
con1->doAction();
return 0;
}
编译:make strategy
有没有一种熟悉的感觉,在基础库里面锁实现就是用的这种模式。