设计模式读书笔记:Strategy(策略)
2015-07-10 21:34:41
意图:
定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Strategy
Context
#include <iostream>
#include "Strategy.h"
namespace NS_STRATEGY {
class Context {
public:
Context() : _strategy(0) {}
virtual ~Context() {}
void contextInterface(void)
{
int a, b;
std::cout << "a=";
std::cin >> a;
std::cout << "b=";
std::cin >> b;
if (_strategy)
_strategy->algorithmInterface(a, b);
}
void setStrategy(Strategy *strategy)
{
_strategy = strategy;
}
private:
Strategy *_strategy;
};
} /* namespace NS_STRATEGY */
Strategy
namespace NS_STRATEGY {
class Strategy {
public:
Strategy() {}
virtual ~Strategy() {}
virtual void algorithmInterface(int a, int b) = 0;
};
} /* namespace NS_STRATEGY */
ConcreteStrategyA
#include <iostream>
#include "Strategy.h"
namespace NS_STRATEGY {
class ConcreteStrategyA : public Strategy
{
public:
ConcreteStrategyA() {}
virtual ~ConcreteStrategyA() {}
virtual void algorithmInterface(int a, int b)
{
std::cout << "a+b = " << a+b << std::endl;
}
};
} /* namespace NS_STRATEGY */
ConcreteStrategyB
#include <iostream>
#include "Strategy.h"
namespace NS_STRATEGY {
class ConcreteStrategyB : public Strategy
{
public:
ConcreteStrategyB() {}
virtual ~ConcreteStrategyB() {}
virtual void algorithmInterface(int a, int b)
{
std::cout << "a-b = " << a-b << std::endl;
}
};
} /* namespace NS_STRATEGY */
main
#include "Strategy/Context.h"
#include "Strategy/ConcreteStrategyA.h"
#include "Strategy/ConcreteStrategyB.h"
using namespace NS_STRATEGY;
int main(void)
{
Context c;
ConcreteStrategyA csa;
ConcreteStrategyB csb;
c.setStrategy(&csa);
c.contextInterface();
c.setStrategy(&csb);
c.contextInterface();
}
附加: