赞
踩
运行在VS2022,x86,Debug下。
//抽象策略类:行为策略接口 class AIStrategy { public: virtual void action() = 0; }; //具体策略类:寻路决策类 class FindWayStrategy :public AIStrategy { public: void action() { cout << "Finding a way" << endl; } }; //具体策略类:攻击决策类 class AttackStrategy :public AIStrategy { public: void action() { cout << "attacking" << endl; } }; //具体策略类:躲避决策类 class AvoidStrategy :public AIStrategy { public: void action() { cout << "avoiding" << endl; } }; //上下文类,负责使用策略对象 class Context { private: AIStrategy* aiStrategy; //抽象策略类指针 public: void setStrategy(AIStrategy* strategy) { aiStrategy = strategy;} //设置策略 void action() const //行为 { if (aiStrategy) { aiStrategy->action();} } }; int main() { FindWayStrategy* findWayStrategy = new FindWayStrategy(); AttackStrategy* attackStrategy = new AttackStrategy(); //算法的选择与使用独立开来 Context context; context.setStrategy(findWayStrategy); //选择策略1 context.action(); //使用 context.setStrategy(attackStrategy); //选择策略2 context.action(); //使用 delete findWayStrategy; delete attackStrategy; return 0; }
注意 :内存释放问题,这里手动释放子类对象。因为将基类析构函数声明为虚函数,当delete基类指针时,会调用子类析构函数,但它只会释放指向的子类对象(某个策略),其余子类对象是无法释放的(其余策略)。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。