定义:将一系列相关算法封装成算法簇,使它们可以相互替换。使算法可以独立于使用者而变换。
适用场景:当类的行为经常发生变化时,可将其行为提取出来,将不同的行为封装成一个算法簇,对使用者只提供一个抽象接口。这样也满足了OO三大原则:封装变化,针对接口编程,多用组合少用继承.
组成:
strategy: 定义所有支持的算法的公共接口
concrete strategy: 实现了具体的算法行为,继承于strategy。
Context :用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
UML图:
代码:
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#include <time.h>
#define LL long long
using namespace std;
// 定义一个武器的接口,英雄可以使用不同的武器,并且可以替换武器
class weapon
{
public:
virtual void use_weapon()=0;
};
class sword:public weapon
{
public:
void use_weapon()
{
puts("use a sword");
}
};
class axe:public weapon
{
public:
void use_weapon()
{
puts("use a axe");
}
};
// 定义使用weapon的hero
class hero
{
private:
weapon *weap;
public:
hero(weapon *p):weap(p) {}
void change_weap(weapon *p)
{
delete weap;
weap = p;
}
void attack()
{
weap->use_weapon();
}
};
int main()
{
hero combatant(new sword);
combatant.attack();
combatant.change_weap(new axe);
combatant.attack();
}