按照自己的理解就是:
一個(gè)策略完成的方法有多種,具體的實(shí)現(xiàn)類里面包含一個(gè)策略虛基類的指針为流,根據(jù)子類實(shí)例化的類調(diào)用具體方法
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
有沒(méi)有一種熟悉的感覺(jué),在基礎(chǔ)庫(kù)里面鎖實(shí)現(xiàn)就是用的這種模式俘侠。