策略模式:定义算法家族并分别封装起来,让它们之间可以互相替换,算法的变化不会影响使用的客户。
简化单元测试
在不同时间对应不同的业务规则,可以考虑策略模式处理这种变化的可能性。
单纯的策略模式需要客户端去知道每个策略的类名,可以和简单工厂模式结合进行隐藏。
/*
2021.09.29 策略模式(Strategy)
策略模式:定义算法家族并分别封装起来,让它们之间可以互相替换,算法的变化不会影响使用的客户。
*/
#include <iostream>
using namespace std;
/*黑马程序员--人物武器策略*/
class WeaponStrategy {
public:
virtual void UseWeapon() = 0;
};
class Knife :public WeaponStrategy {
public:
virtual void UseWeapon() {
cout << "Use Knife" << endl;
}
};
class AK47 :public WeaponStrategy {
public:
virtual void UseWeapon() {
cout << "Use Ak47" << endl;
}
};
class Character {
public:
void setWeapon(WeaponStrategy* weapon) {
this->pWeapon = weapon;
}
void ThrowWeapon() {
this->pWeapon->UseWeapon();
}
public:
WeaponStrategy* pWeapon;
};
void testWeapon() {
Character* character = new Character;
WeaponStrategy* knife = new Knife;
WeaponStrategy* ak47 = new AK47;
character->setWeapon(knife);
character->ThrowWeapon();
character->setWeapon(ak47);
character->ThrowWeapon();
delete knife;
delete ak47;
delete character;
}
int main() {
testWeapon();
system("pause");
return 0;
}