Strategy策略模式
作用:定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
UML图:
Strategy模式将逻辑(算法)封装到一个类(Context)里面,通过组合的方式将具体算法的实现在组合对象中实现,再通过委托的方式将抽象接口的实现委托给组合对象实现
将算法的逻辑抽象接口(DoAction)封装到一个类中(Context),再通过委托的方式将具体的算法实现委托给具体的Strategy类来实现(ConcreteStrategeA类)
Stragegy类,定义所有支持的算法的公共接口
ConcreteStrategy,封装了具体的算法或行为,继承于Strategy
Context,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类于使用算法类之间的耦合。
策略模式的Strategy类层次为Context定义了一系列的可供重用的算法或行为。继承有助于析取出这些算法中的公共功能。
策略模式的优点是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
在基本的策略模式中,选择所用具体实现的职责由客户端对象承担,并转给策略模式的Context对象。这本身并没有解除客户端需要选择判断的压力。
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//抽象的策略(抽象的武器)
class AbstractStrategy
{
public:
//纯虚函数, 使用具体武器的策略,
virtual void useWeapon() = 0;
};
class KnifeStrategy :public AbstractStrategy
{
public:
virtual void useWeapon() {
cout << "使用匕首,进行近战攻击" << endl;
}
};
class AkStrategy :public AbstractStrategy
{
public:
virtual void useWeapon() {
cout << "使用ak 进行远程攻击" << endl;
}
};
class Hero
{
public:
Hero()
{
strategy = NULL;
}
void setStrategy(AbstractStrategy *strategy)
{
this->strategy = strategy;
}
//攻击方法
void fight() {
cout << "英雄开始战斗了" << endl;
this->strategy->useWeapon();
}
private:
//拥有一个 使用攻击策略的抽象成员
AbstractStrategy *strategy;
};
int main(void)
{
AbstractStrategy *knife = new KnifeStrategy;
AbstractStrategy *ak47 = new AkStrategy;
Hero *hero = new Hero;
cout << "远程兵来了, 更换远程攻击" << endl;
hero->setStrategy(ak47);
hero->fight();
cout << "近战兵 来了, 更换近战的攻击" << endl;
hero->setStrategy(knife);
hero->fight();
return 0;
}