策略模式(c++)

#include<iostream>

using namespace std;

//武器策略
class WeaponStrategy {
public:
	virtual void UseWeapon() = 0;
};
//匕首策略
class KnifeStrategy :public WeaponStrategy {
public:
	virtual void UseWeapon() {
		cout << "使用匕首" << endl;
	}
};
//AK策略
class AK47Strategy :public WeaponStrategy {
public:
	virtual void UseWeapon() {
		cout << "使用AK47" << endl;
	}
};
class Character {
public:
	//设置武器策略
	void setWeaponStrategy(WeaponStrategy* weaponStrategy) {
		pWeaponStrategy = weaponStrategy;
	}
	void UseWeapon() {
		pWeaponStrategy->UseWeapon();
	}
private:
	WeaponStrategy* pWeaponStrategy;
};
void test() {
	Character* character = new Character;
	WeaponStrategy* strategy = new KnifeStrategy;
	character->setWeaponStrategy(strategy);
	character->UseWeapon();

	delete character;
	delete strategy;
}
int main() {
	test();



	cin.get();
	return 0;
}

  

posted @ 2024-03-25 17:48  dmfsimle  阅读(3)  评论(0编辑  收藏  举报