命令转发(准备用到异步变同步模式)

本文介绍了一个使用C++实现的命令模式示例,包括抽象命令接口、具体命令类和客户端调用逻辑。通过Boost库和标准模板库实现了命令的创建、执行及取消等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include <boost/function.hpp>
#include <vector>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <conio.h>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace std;
using namespace boost;

class ICommand
{
public:
	virtual void Execute() = 0;
	virtual ~ICommand() { }
};

class DoCommand : public ICommand
{
private:
	int n_;
public:
	DoCommand(int n) : n_(n) 
	{
		//cout << "DoCommand()" << endl;
	}
	void Execute()
	{
		cout << "DoCommand::Execute() n = " << n_ << endl;
	}
	~DoCommand()
	{
		cout << "~DoCommand " << n_ << endl;
	}
};

class AllocCommand : public ICommand
{
private:
	int		m_MemorySize;
	int*	m_pMemory;
public:
	AllocCommand(int memorySize) : m_MemorySize(memorySize), m_pMemory(new int[m_MemorySize])
	{
		//cout << "AllocCommand " << m_MemorySize << "bytes, address = " << m_pMemory << endl;
	}
	~AllocCommand()
	{
		cout << "~AllocCommand " << m_MemorySize << endl;
		delete[] m_pMemory;
		m_pMemory = NULL;
		m_MemorySize = 0;
	}

	void Execute()
	{
		cout << "AllocMemory::Execute() n = " << m_MemorySize << endl;
	}
};
void StopService(boost::asio::io_service& ios)
{
	while(1)
	{
		if(_kbhit())
		{
			ios.stop();
			break;
		}
	}
}
void RunIoService(boost::asio::io_service& ios)
{
	while(1)
	{
		try
		{
			ios.run();
			break;
		}
		catch(...)
		{
		}
	}
}
typedef function<void ()> FCommand;
typedef boost::shared_ptr<FCommand> CommandPtr;

void HandleEvent(CommandPtr pCommand)
{
	(*pCommand)();
}
void main()
{

	boost::shared_ptr<AllocCommand> pAlloc;
	boost::shared_ptr<DoCommand> pDo;
	std::vector<CommandPtr> cmdArray;
	std::vector<boost::weak_ptr<FCommand> > weakArray;
	cmdArray.reserve(100);
	for (int i = 1; i <= 10; ++i)
	{
		CommandPtr pCmd;
		boost::weak_ptr<FCommand> weak;
		if (i % 2)
		{
			pAlloc = boost::make_shared<AllocCommand>(i);
			pCmd.reset(new FCommand(bind(&ICommand::Execute, pAlloc)));
		}
		else
		{
			pDo = boost::make_shared<DoCommand>(i);
			pCmd.reset(new FCommand(bind(&ICommand::Execute, pDo)));
		}
		weak = pCmd;
		weakArray.push_back(weak);
		cmdArray.push_back(pCmd);
	}
	boost::asio::io_service ioservice;
	boost::asio::io_service::work work(ioservice);
	boost::asio::io_service::strand strand(ioservice);

	boost::thread t(&RunIoService, boost::ref(ioservice));
	boost::thread s(&StopService, boost::ref(ioservice));
	for (int i = 0; i < cmdArray.size(); ++i)
	{
		strand.post(boost::bind(&HandleEvent, cmdArray[i]));
	}	
	cmdArray.clear();
	t.join();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值