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();
}