1 策略模式有点类似状态模式,不过策略的调用链切换是固定的。
A A can not do -> B B can not do -> C do
2 代码
#include <iostream>
#include <stdio.h>
#include <string>
class StrategyBase {
public:
virtual void DoOperation(int a, int b) = 0;
};
class StrategyDad :public StrategyBase{
public:
void DoOperation(int a, int b) {
printf("this is dad DoOperation %d\n", a + b);
}
};
class StrategyHusband :public StrategyBase{
public:
void DoOperation(int a, int b) {
printf("this is Husband DoOperation %d\n", a - b);
}
};
class StrategySon :public StrategyBase{
public:
void DoOperation(int a, int b) {
printf("this is Son DoOperation %d\n", a * b);
}
};
class Context
{
public:
StrategyBase *st;
Context(StrategyBase *s) {
st = s;
}
void ExecuteStrategy(int a, int b) {
if (st == NULL)
st = new StrategyDad();
if (a >= 200 || b >= 300) {
Swap(new StrategySon);
} else if (a >= 20 || b >= 30) {
Swap(new StrategyHusband);
} else {
Swap(new StrategyDad);
}
st->DoOperation(a, b);
}
void Swap(StrategyBase *s) {
if (st) delete st;
st = s;
}
};
int main()
{
Context *ct = new Context(new StrategyHusband());
ct->ExecuteStrategy(2, 3);
ct->Swap(new StrategyDad);
ct->ExecuteStrategy(20, 30);
ct->Swap(new StrategySon);
ct->ExecuteStrategy(200, 300);
return 0;
}