设计模式之Strategy模式

Strategy模式是对算法的封装,在处理一个问题的时候,可能有多种不同的处理方式,这些处理方式的接口(输入参数、输出参数)都是一致的,那么就可以采用Strategy模式对这些算法进行封装。

//基类AbstractStrategy.h
#ifndef ABSTRACT_STRATEGY_H_
#define ABSTRACT_STRATEGY_H_

#include<iostream>

class AbstractStrategy
{
public:
	virtual ~AbstractStrategy() {}

	virtual void Algorithm() = 0;	
};

#endif // !ABSTRACT_STRATEGY_H_
//StrategyA.h
#ifndef STRATEGYA_H_
#define STRATEGYA_H_

#include "AbstractStrategy.h"

class StrategyA :
	public AbstractStrategy
{
public:
	StrategyA();
	~StrategyA();

	void Algorithm() override;
};

#endif // !STRATEGYA_H_
//StrategyA.cpp
#include "StrategyA.h"

StrategyA::StrategyA()
{
}

StrategyA::~StrategyA()
{
}

void StrategyA::Algorithm()
{
	std::cout << "this is StrategyA::Algorithm\n";
}
//StrategyB.h
#ifndef STRATEGYB_H_
#define STRATEGYB_H_

#include "AbstractStrategy.h"

class StrategyB :
	public AbstractStrategy
{
public:
	StrategyB();
	~StrategyB();
	void Algorithm() override;
};

#endif //STRATEGYB_H_
//StrategyB.cpp
#include "StrategyB.h"

StrategyB::StrategyB()
{
}

StrategyB::~StrategyB()
{
}

void StrategyB::Algorithm()
{
	std::cout << "this is StrategyB::Algorithm\n";
}
//Context.h
#ifndef CONTEXT_H_
#define CONTEXT_H_

#include"AbstractStrategy.h"

class Context
{
private:
	AbstractStrategy *m_strategy;
public:
	Context(AbstractStrategy *strategy);
	~Context();

	void func();
};
#endif // !CONTEXT_H_
//Context.cpp
#include "Context.h"

Context::Context(AbstractStrategy * strategy):m_strategy(strategy)
{
}

Context::~Context()
{
	if (m_strategy)
	{
		delete m_strategy;
		m_strategy = nullptr;
	}	
}

void Context::func()
{
	if (m_strategy)
	{
		m_strategy->Algorithm();
	}
}
//main.cpp
#include<iostream>
#include"Context.h"
#include"StrategyA.h"
#include"StrategyB.h"
using namespace std;

int main() {

	AbstractStrategy *strategy1 = new StrategyA();
	Context *con1 = new Context(strategy1);
	con1->func();

	AbstractStrategy *strategy2 = new StrategyB();
	Context *con2 = new Context(strategy2);
	con2->func();

	delete con1;
	delete con2;

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值