class Strategy
{
public:
Strategy() {};
virtual ~Strategy() {};
virtual void getCurrentStrategy() = 0;
};
class Strategy1 : public Strategy
{
public:
Strategy1() {};
~Strategy1() {};
virtual void getCurrentStrategy(){ cout << "当前使用的策略是Strategy1" << endl; }
};
class Strategy2 : public Strategy
{
public:
Strategy2() {};
~Strategy2() {};
virtual void getCurrentStrategy(){ cout << "当前使用的策略是Strategy2" << endl; }
};
class Strategy3 : public Strategy
{
public:
Strategy3() {};
~Strategy3() {};
virtual void getCurrentStrategy(){ cout << "当前使用的策略是Strategy3" << endl; }
};
class Context
{
private:
Strategy *pStrategy = nullptr;
public:
Context(Strategy *pStrategyArg) : pStrategy(pStrategyArg){}
void ContextInterface(){
pStrategy->getCurrentStrategy();
}
};
void client() {
Strategy *pStrategy1 = new Strategy1();
Context *pContext1 = new Context(pStrategy1);
pContext1->ContextInterface();
if (pStrategy1) delete pStrategy1;
if (pContext1) delete pContext1;
Strategy *pStrategy2 = new Strategy2();
Context *pContext2 = new Context(pStrategy2);
pContext2->ContextInterface();
if (pStrategy2) delete pStrategy2;
if (pContext2) delete pContext2;
Strategy *pStrategy3 = new Strategy3();
Context *pContext3 = new Context(pStrategy3);
pContext3->ContextInterface();
if (pStrategy3) delete pStrategy3;
if (pContext3) delete pContext3;
}
int main() {
client();
return 0;
}