1 下面是策略模式的类图:
Context(应用场景):
1、需要使用ConcreteStrategy提供的算法。
2、内部维护一个Strategy的实例。
3、负责动态设置运行时Strategy具体的实现算法。
4、负责跟Strategy之间的交互和数据传递。
Strategy(抽象策略类):定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,Context使用这个接口调用不同的算法,一般使用接口或抽象类实现。
ConcreteStrategy(具体策略类):实现了Strategy定义的接口,提供具体的算法实现
2 策略模式就是将算法进行封装,ConcreteStrategyA ConcreteStrategyB ConcreteStrategyC 是不同的算法,就好像玩CS中武器有AK47的手枪,也有尖刀,用户可以随意使用这两种武器,所以把这个算法封装在Strategy类中。
3 代码实例:
#include<iostream>
using namespace std;
class Weapon //<span style="font-family: Arial; font-size: 14px; line-height: 26px;">Strategy</span>
{
public:
virtual void useWeapon() = 0;
};
class Ak47:public Weapon //ConcreteStrategyA
{
public:
void useWeapon()
{
cout<<"USE Ak47 to shoot"<<endl;
}
};
class Knife:public Weapon //ConcreteStrategyB
{
public:
void useWeapon()
{
cout<<"USE Knife to kill"<<endl;
}
};
class Character //Context
{
public:
Character()
{
m_Weapon = NULL ;
}
void setWeapon(Weapon *w)
{
m_Weapon = w;
}
virtual void fight() =0;
protected:
Weapon * m_Weapon;
};
class King:public Character
{
public:
void fight()
{
if(this->m_Weapon == NULL)
{
cout<<"You don't have a weapon,Please set weapon!"<<endl;
}
else
{
m_Weapon->useWeapon();
}
}
};
// 下面是主程序代码
// Strategy.cpp : 定义控制台应用程序的入口点。
//
/*策略模式*/
#include "stdafx.h"
#include"Weapon.hpp"
int _tmain(int argc, _TCHAR* argv[])
{
Weapon *ak47 = new Ak47();
Weapon *knife = new Knife();
Character *king = new King();
king->fight();
king->setWeapon(ak47);
king->fight();
king->setWeapon(knife);
king->fight();
system("pause");
return 0;
}