(一)策略模式C++

main(),赵云

CContext,锦囊

IStrategy,策略接口

CBackDoor,策略之一

CGivenGreenLight,策略之二

CBlockEnemy,策略之三

说明:一个策略放到一个锦囊里。当用的时候,找到这个锦囊,从锦囊里拿出策略来使用。

注意:锦囊只是简单的装载和调用策略,锦囊里没有逻辑。策略会有更大的自主权,运行更多的逻辑

//Strategy.h

#ifndef STRATEGY_H_
#define STRATEGY_H_

class Strategy
{
public:
	Strategy();
	~Strategy();
	virtual void Operate() = 0;
};



class BackDoor:public Strategy
{
public:
	BackDoor();
	~BackDoor();
	void Operate();
};

class GivenGreenLight:public Strategy
{
public:
	GivenGreenLight();
	~GivenGreenLight();
	void Operate();
};

class BlockEnemy:public Strategy
{
public:
	BlockEnemy();
	~BlockEnemy();
	void Operate();
};

#endif
//Strategy.cpp

#include "Strategy.h"
#include <iostream>

using namespace std;

Strategy::Strategy() {}
Strategy::~Strategy() {}

BackDoor::BackDoor() {}
BackDoor::~BackDoor() {}

void BackDoor::Operate()
{
	cout<<"找叫人帮忙,给孙权施压"<<endl;
}

GivenGreenLight::GivenGreenLight() {}
GivenGreenLight::~GivenGreenLight() {}
void GivenGreenLight::Operate()
{
	cout<<"求吴国开个绿灯,放行"<<endl;
}

BlockEnemy::BlockEnemy() {}
BlockEnemy::~BlockEnemy() {}
void BlockEnemy::Operate()
{
	cout<<"孙夫人断后,阻挡追兵"<<endl;
}

//Context.h

#ifndef CONTEXT_H_
#define CONTEXT_H_

#include "Strategy.h"

class Context
{
public:
	Context(Strategy *pStrategy);
	~Context();
	void Operate();
private:
	Strategy *m_pStrategy;
};

#endif

//Context.cpp

#include "Context.h"
#include <iostream>

using namespace std;

Context::Context(Strategy *pStrategy)
{
	m_pStrategy = pStrategy;
}
Context::~Context()
{
	delete this->m_pStrategy;
}
void Context::Operate()
{
	this->m_pStrategy->Operate();
}

//main.cpp

#include <iostream>
#include <stdlib.h>
#include "Strategy.h"
#include "Context.h"

using namespace std;

int main()
{
	Context *pContext;
	
	cout<<"------刚到吴国请拆第一个锦囊-------"<<endl;
	pContext = new Context(new BackDoor());
	pContext->Operate();
	delete pContext;

	cout<<"-----刘备不思蜀,就要拆第二个------"<<endl;
	pContext = new Context(new GivenGreenLight());
	pContext->Operate();
	delete pContext;

	cout<<"------孙权的追兵来了,就拆第三个------"<<endl;
	pContext = new Context(new BlockEnemy());
	pContext->Operate();
	delete pContext;

	return 0;
}

相对来说这个是比较好理解的例子

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值