关闭

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

标签: 设计模式读书笔记Strategy策略
402人阅读 评论(0) 收藏 举报
分类:

意图:

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

结构图:来自 《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();
}
附加:

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:86097次
    • 积分:1350
    • 等级:
    • 排名:千里之外
    • 原创:66篇
    • 转载:0篇
    • 译文:0篇
    • 评论:40条
    文章分类
    最新评论