1.策略模式
策略模式定义了一系列的算法,并将一个算法封装起来,而且是他们还可以相互替换,策略模式让算法独立于使用它的客户而独立变化
2.代码实现
#include <iostream>
#include <vector>
#include <algorithm>
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 Charcter
{
public:
void setWeapon(WeaponStrategy* weapon)
{
this->pWeapon = weapon;
}
void ThrowWeapon()
{
this->pWeapon->UseWeapon();
}
WeaponStrategy* pWeapon;
};
int main()
{
{
//创建角色
Charcter* t_charater = new Charcter;
//武器策略
WeaponStrategy* t_knife = new Knife;
WeaponStrategy* t_ak47 = new AK47;
t_charater->setWeapon(t_knife);
t_charater->ThrowWeapon();
t_charater->setWeapon(t_ak47);
t_charater->ThrowWeapon();
delete t_knife;
delete t_ak47;
delete t_charater;
t_ak47 = nullptr;
t_charater = nullptr;
t_knife = nullptr;
}
system("pause");
return 0;
}