和Template同樣的目的,只不過實現手法是組合 而不是Template模式的繼承,解決了繼承所帶來的弊端。算法
問題:ide
爲了給業務邏輯(算法)具體的實現和抽象的接口之間的解耦。this
把算法 (業務邏輯)封裝到一個Contex類中經過組合的方式,實如今組合對象中,經過委託的方式將抽象接口的實現委託給組合對象的實現State模式也有相似區別code
定義了一些列的算法,而且封裝起來,使他們能夠相互替換,策略模式讓算法獨立於客戶的變化而獨立變化
對象
#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(); }