panshiqu的专栏

给自己维护的项目打个广告:欢迎关注《休闲益智游戏》微信公众号

设计模式读书笔记:Strategy(策略)

意图:

定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。

结构图:来自 《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();
}
附加:
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/panshiqu/article/details/46835257
个人分类: 设计模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

设计模式读书笔记:Strategy(策略)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭