前文回顾
单例模式(一)
单例模式(二)
观察者模式
简单工厂模式
工厂方法模式(一)
工厂方法模式(二)
抽象工厂模式(一)
抽象工厂模式(二)
原型模式
外观模式
中介者模式
代理模式
装饰者模式
前言
所谓策略即解决一件事情的算法、或者方法,是一些具有相同签名的函数,把策略封装成对象(可以是类对象、也可以是任何形式的可调用对象),这样便可把策略定义为类的数据成员,就可以动态的设置数据成员的值,即更换策略。
实现举例
- 场景描述
假设一个简单的游戏场景:玩家角色有攻击的动作,但根据装配武器的不同,会有不同的攻击效果。 - 策略基类
#include <iostream>
using namespace std;
class Attack
{
public:
virtual void AttackMethod() = 0;
~Attack(){} ;
};
- 策略派生类
①.普通攻击
#include "attack.h"
class CommonAttack : public Attack
{
public:
using Attack::Attack;
void AttackMethod() override
{
cout <<"普通攻击,伤害+2"<<endl;
}
};
②.匕首攻击
#include "attack.h"
class DaggerAttack : public Attack
{
public:
using Attack::Attack;
void AttackMethod() override
{
cout <<"匕首攻击,伤害+10"<<endl;
}
};
③.手枪攻击
#include "attack.h"
class GunAttack : public Attack
{
public:
using Attack::Attack;
void AttackMethod() override
{
cout << "手枪攻击,伤害+50"<<endl;
}
};
- 策略使用者
#include "commonattack.h"
#include <memory>
class Plaer
{
public:
Plaer(const string &m_name,shared_ptr<Attack> m_attack = make_shared<CommonAttack>()):name(m_name),attack(m_attack){}
void showAttack()
{
attack->AttackMethod();
}
void setAttack(shared_ptr<Attack> m_attack)
{
attack = m_attack;
}
private:
string name;
shared_ptr<Attack> attack;
};
- 客户端调用
#include "commonattack.h"
#include "daggerattack.h"
#include "gunattack.h"
#include "plaer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout <<"***英雄刚出场,自带普通攻击***"<<endl;
Plaer * hero = new Plaer("王者");
hero->showAttack();
cout << "***角色升级,获得匕首***"<<endl;
shared_ptr<DaggerAttack> dagger = make_shared<DaggerAttack>();
hero->setAttack(dagger);
hero->showAttack();
cout << "***角色升级,获得手枪***"<<endl;
shared_ptr<GunAttack> gun = make_shared<GunAttack>();
hero->setAttack(gun);
hero->showAttack();
return a.exec();
}