设计模式-行为-Strategy(策略)模式
和Template一样的目的,只不过实现手法是组合 而不是Template模式的继承,解决了继承所带来的弊端。
问题:
为了给业务逻辑(算法)具体的实现和抽象的接口之间的解耦。
把算法 (业务逻辑)封装到一个Contex类中通过组合的方式,实现在组合对象中,通过委托的方式将抽象接口的实现委托给组合对象的实现State模式也有类似区别
定义了一些列的算法,并且封装起来,使他们可以相互替换,策略模式让算法独立于客户的变化而独立变化
#include "PublicHeaders.h" class Strategy { public: virtual void AlgrithmInterface() = 0; }; class ConCreateStrategy :public Strategy { public: void AlgrithmInterface()override { cout << __FUNCTION__ << endl; } }; class Contex { public: Contex(Strategy *strategy) { this->strategy = strategy; } void DoAction() { this->strategy->AlgrithmInterface(); } private: Strategy*strategy; }; /** * @brief test function for strategy pattern */ void testStrategy() { Contex* contex = new Contex(new ConCreateStrategy); contex->DoAction(); }
例2
武器系统
class WeaponStrategy { public: virtual void doFire() = 0; }; class GaTlingGun_Strategy :public WeaponStrategy { public: virtual void doFire()override { } }; class PistolGun_Strategy :public WeaponStrategy { public: virtual void doFire()override { } }; class PlayerContex { public: void Fire() { weapon->doFire(); } void setWeapon(WeaponStrategy *strategy) { this->weapon = strategy; } WeaponStrategy*weapon; }; void test() { PlayerContex*player = new PlayerContex; player->setWeapon(new GaTlingGun_Strategy); player->Fire(); }