main(),赵云
CContext,锦囊
IStrategy,策略接口
CBackDoor,策略之一
CGivenGreenLight,策略之二
CBlockEnemy,策略之三
说明:一个策略放到一个锦囊里。当用的时候,找到这个锦囊,从锦囊里拿出策略来使用。
注意:锦囊只是简单的装载和调用策略,锦囊里没有逻辑。策略会有更大的自主权,运行更多的逻辑
//Strategy.h
#ifndef STRATEGY_H_
#define STRATEGY_H_
class Strategy
{
public:
Strategy();
~Strategy();
virtual void Operate() = 0;
};
class BackDoor:public Strategy
{
public:
BackDoor();
~BackDoor();
void Operate();
};
class GivenGreenLight:public Strategy
{
public:
GivenGreenLight();
~GivenGreenLight();
void Operate();
};
class BlockEnemy:public Strategy
{
public:
BlockEnemy();
~BlockEnemy();
void Operate();
};
#endif
//Strategy.cpp
#include "Strategy.h"
#include <iostream>
using namespace std;
Strategy::Strategy() {}
Strategy::~Strategy() {}
BackDoor::BackDoor() {}
BackDoor::~BackDoor() {}
void BackDoor::Operate()
{
cout<<"找叫人帮忙,给孙权施压"<<endl;
}
GivenGreenLight::GivenGreenLight() {}
GivenGreenLight::~GivenGreenLight() {}
void GivenGreenLight::Operate()
{
cout<<"求吴国开个绿灯,放行"<<endl;
}
BlockEnemy::BlockEnemy() {}
BlockEnemy::~BlockEnemy() {}
void BlockEnemy::Operate()
{
cout<<"孙夫人断后,阻挡追兵"<<endl;
}
//Context.h
#ifndef CONTEXT_H_
#define CONTEXT_H_
#include "Strategy.h"
class Context
{
public:
Context(Strategy *pStrategy);
~Context();
void Operate();
private:
Strategy *m_pStrategy;
};
#endif
//Context.cpp
#include "Context.h"
#include <iostream>
using namespace std;
Context::Context(Strategy *pStrategy)
{
m_pStrategy = pStrategy;
}
Context::~Context()
{
delete this->m_pStrategy;
}
void Context::Operate()
{
this->m_pStrategy->Operate();
}
//main.cpp
#include <iostream>
#include <stdlib.h>
#include "Strategy.h"
#include "Context.h"
using namespace std;
int main()
{
Context *pContext;
cout<<"------刚到吴国请拆第一个锦囊-------"<<endl;
pContext = new Context(new BackDoor());
pContext->Operate();
delete pContext;
cout<<"-----刘备不思蜀,就要拆第二个------"<<endl;
pContext = new Context(new GivenGreenLight());
pContext->Operate();
delete pContext;
cout<<"------孙权的追兵来了,就拆第三个------"<<endl;
pContext = new Context(new BlockEnemy());
pContext->Operate();
delete pContext;
return 0;
}
相对来说这个是比较好理解的例子