策略模式定义
#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();
}
public:
weaponStrategy *pweapon;
};
void test() {
//创建角色
Character *character = new Character;
//武器策略
weaponStrategy *knife = new Knife;
weaponStrategy *ak47 = new AK47;
character->setWeapon(knife);
character->throwWeapon();
character->setWeapon(ak47);
character->throwWeapon();
delete character;
delete knife;
delete ak47;
}
int main()
{
test();
return 0;
}
运行结果
策略模式优缺点(转载于互联网)
优点:
1、策略模式符合开闭原则。
2、避免使用多重条件转移语句,如if...else...语句、switch 语句
3、使用策略模式可以提高算法的保密性和安全性。
缺点:
1、客户端必须知道所有的策略,并且自行决定使用哪一个策略类。
2、代码中会产生非常多策略类,增加维护难度。