命令模式(Command)

1.目的

   将请求封装成对象(Command),由一个对象(Waiter)统一持有并触发执行,每一个Command都是一个抽象的接口,可以派生为具体的请求内容,并且持有请求的执行者(Receiver),当Waiter统一触发执行之后,每一条命令都调用其执行者执行。


2.代码

command.h

#ifndef COMMAND_H_
#define COMMAND_H_

#include <vector>
#include <string>

class Receiver;

class Command
{
public:
	virtual ~Command();
	virtual void exec() =0;
	virtual std::string getCommandContent() =0;
};

class MuttonCommand:public Command
{
public:
	MuttonCommand(Receiver&);
	void exec();
	std::string getCommandContent();
private:
	Receiver& executor;
};

class ChickenCommand:public Command
{
public:
	ChickenCommand(Receiver&);
	void exec();
	std::string getCommandContent();
private:
	Receiver& executor;
};

class Waiter
{
public:
	void addCommand(Command&);
	void notify();
private:
	std::vector<Command*> commands;
};

class Receiver
{
public:
	virtual ~Receiver();
	virtual void action(Command&) = 0;
};

class Cooker:public Receiver
{
public:
	void action(Command&);
};

class Baker:public Receiver
{
public:
	void action(Command&);
};





#endif /* COMMAND_H_ */

command.cpp

#include "Command.h"
#include <iostream>
using namespace std;

Command::~Command()
{}

MuttonCommand::MuttonCommand(Receiver& arg):executor(arg)
{
}

void MuttonCommand::exec()
{
	executor.action(*this);
}

string MuttonCommand::getCommandContent()
{
	return "a piece of Mutton";
}

ChickenCommand::ChickenCommand(Receiver& arg):executor(arg)
{
}

void ChickenCommand::exec()
{
	executor.action(*this);
}

string ChickenCommand::getCommandContent()
{
	return "a piece of Chicken";
}

void Waiter::addCommand(Command& c)
{
	commands.push_back(&c);
}

void Waiter::notify()
{
	vector<Command*>::iterator iter = commands.begin();

	while(iter != commands.end())
	{
		(*iter)->exec();
		iter++;
	}
}

Receiver::~Receiver()
{}

void Cooker::action(Command& arg)
{
	cout<<"Cooker cooks "<<arg.getCommandContent()<<endl;
}

void Baker::action(Command& arg)
{
	cout<<"Baker cooks "<<arg.getCommandContent()<<endl;
}


void command()
{
	Waiter waiter;
	Cooker cooker;
	Baker baker;

	MuttonCommand m1(cooker);
	ChickenCommand c1(baker);
	MuttonCommand m2(baker);

	waiter.addCommand(m1);
	waiter.addCommand(c1);
	waiter.addCommand(m2);

	waiter.notify();
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值