#include <iostream>
using namespace std;
class IStrategy
{
public:
IStrategy(void){}
virtual ~IStrategy(void){}
virtual void Operate(void) = 0;
};
class CContext
{
public:
CContext(IStrategy *pStrategy)
{
this->m_pStrategy = pStrategy;
}
~CContext(void)
{
delete this->m_pStrategy;
}
void Operate(void)
{
this->m_pStrategy->Operate();
}
private:
IStrategy *m_pStrategy;
};
class CBackDoor : public IStrategy
{
public:
void Operate(void)
{
cout << "调用第一个锦囊" << endl;
}
};
class CGivenGreenLight :public IStrategy
{
public:
void Operate(void)
{
cout << "调用第二个锦囊" << endl;
}
};
class CBlockEnemy :public IStrategy
{
public:
void Operate(void)
{
cout << "调用第三个锦囊" << endl;
}
};
int main()
{
CContext *pContext;
pContext = new CContext(new CBackDoor());
pContext->Operate();
delete pContext;
pContext = new CContext(new CGivenGreenLight());
pContext->Operate();
delete pContext;
pContext = new CContext(new CBlockEnemy());
pContext->Operate();
delete pContext;
IStrategy* ist = new CBackDoor();//为什么不直接用这种?
ist->Operate();
return 0;
}
Strategy策略模式
最新推荐文章于 2025-05-09 14:10:14 发布