/*
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们还可以相互替换,策略模式让算法独立于使用它的客户而独立变化。
*/
# 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 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(int argc, char *argv[])
{
test01();
return 0;
}
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们还可以相互替换,策略模式让算法独立于使用它的客户而独立变化。
*/
# 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 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(int argc, char *argv[])
{
test01();
return 0;
}