策略模式:定义了一系列算法,并将每一个算法封装起来,而且使它们还可以相互替换。
策略模式让算法独立于使用它的客户而独立变化。
代码如下:
#include <iostream>
using namespace std;class WeaponStrategy
{
public:virtual void useWeapon() = 0;
};class Knife :public WeaponStrategy
{
public:virtual void useWeapon(){cout << "使用匕首" << endl;}
};class AK47 :public WeaponStrategy
{
public:virtual void useWeapon(){cout << "使用AK47" << endl;}
};class Character
{
public:void setWeapon(WeaponStrategy *weapon){this->pWeapon = weapon;}void ThrowWeapon(){this->pWeapon->useWeapon();}WeaponStrategy *pWeapon;
};void test01()
{Character *character = new Character;WeaponStrategy *knife = new Knife;WeaponStrategy *ak47 = new AK47;character->setWeapon(knife);character->ThrowWeapon();character->setWeapon(ak47);character->ThrowWeapon();delete ak47;delete knife;delete character;
}int main()
{test01();return 0;
}
测试结果: