1. 策略模式定义一系列的算法,把他们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。属于行为型模式。
2. 适用场景
(1)许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
(2)需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间 /时间权衡的算法。当这些变体实现为一个算法的类层次时,可以使用策略模式。
(3) 算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。
(4)一个类定义了多种行为 , 并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的 Strategy类中以代替这些条件语句。
3. 举例说明
一个人想吃水果,拿到苹果就吃苹果,拿到香蕉就吃香蕉。
#include <iostream>
using namespace std;
class FruitStrategy {
public:
virtual void eatFruit() = 0;
};
class Apple : public FruitStrategy {
public:
void eatFruit()
{
cout << "eat apple" << endl;
}
};
class Banana : public FruitStrategy {
public:
void eatFruit()
{
cout << "eat banana" << endl;
}
};
class People {
public:
void setFruit(FruitStrategy *fruit)
{
mFruitStrategy = fruit;
}
void eatFruitStrategy()
{
mFruitStrategy->eatFruit();
}
private:
FruitStrategy *mFruitStrategy;
};
int main()
{
cout << "Strategy:" << endl;
People *p = new People();
FruitStrategy *aFruitStrategy = new Apple();
p->setFruit(aFruitStrategy);
p->eatFruitStrategy();
FruitStrategy *bFruitStrategy = new Banana();
p->setFruit(bFruitStrategy);
p->eatFruitStrategy();
return 0;
}
4. 结果
END.