1、命令接口类Command定义
#ifndef COMMAND_H
#define COMMAND_H
class Command
{
public:
virtual void execute() = 0;
virtual void unExecute() = 0;
};
#endif
2、命令接口实现类ConcreteCommand定义
#ifndef CONCRETECOMMAND_H
#define CONCRETECOMMAND_H
#include <stdio.h>
#include "Command.h"
#include "Receiver.h"
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver* recv);
~ConcreteCommand();
void execute();
void unExecute();
private:
Receiver* m_recv;
};
#endif
3、命令接口实现类ConcreteCommand实现
#include "ConcreteCommand.h"
ConcreteCommand::ConcreteCommand(Receiver* recv) : m_recv(recv)
{
}
ConcreteCommand::~ConcreteCommand()
{
}
void ConcreteCommand::execute()
{
if(m_recv != NULL)
{
m_recv->action();
}
}
void ConcreteCommand::unExecute()
{
if(m_recv != NULL)
{
m_recv->unAction();
}
}
4、命令接受者Receiver定义
#ifndef RECEIVER_H
#define RECEIVER_H
class Receiver
{
public:
virtual void action() = 0;
virtual void unAction() = 0;
};
#endif
5、命令接受者实现类ConcreteReceiver定义
#ifndef CONCRETERECEIVER_H
#define CONCRETERECEIVER_H
#include "Receiver.h"
class ConcreteReceiver : public Receiver
{
public:
ConcreteReceiver(char*);
~ConcreteReceiver();
void action();
void unAction();
private:
char* m_name;
};
#endif
6、命令接受者实现类ConcreteReceiver实现
#include <stdio.h>
#include "ConcreteReceiver.h"
ConcreteReceiver::ConcreteReceiver(char* name) : m_name(name)
{
}
ConcreteReceiver::~ConcreteReceiver()
{
}
void ConcreteReceiver::action()
{
printf("ConcreteReceiver::action() %s/n",m_name);
}
void ConcreteReceiver::unAction()
{
printf("ConcreteReceiver::unAction() %s/n",m_name);
}
7、命令发送者Involer定义
#include <list>
#include "Command.h"
using namespace std;
class Invoker
{
public:
Invoker();
~Invoker();
void addCommand(Command*);
void removeCommand(Command*);
void doCommand();
void unDoCommand();
private:
list<Command*> m_cmdlist;
list<Command*> m_oldcmd;
};
#endif
8、命令发送者Invoker实现
#include "Invoker.h"
Invoker::Invoker()
{
}
Invoker::~Invoker()
{
}
void Invoker::addCommand(Command* cmd)
{
m_cmdlist.push_back(cmd);
}
void Invoker::removeCommand(Command* cmd)
{
m_cmdlist.remove(cmd);
}
void Invoker::doCommand()
{
while(!m_cmdlist.empty())
{
Command* cmd = m_cmdlist.front();
m_cmdlist.pop_front();
cmd->execute();
m_oldcmd.push_back(cmd);
}
}
void Invoker::unDoCommand()
{
while(!m_oldcmd.empty())
{
Command* cmd = m_oldcmd.back();
m_oldcmd.pop_back();
cmd->unExecute();
}
}
9、客户使用者Client
#include "Invoker.h"
#include "Command.h"
#include "ConcreteCommand.h"
#include "ConcreteReceiver.h"
#include "Receiver.h"
int main()
{
Invoker* inv = new Invoker();
Receiver* recv0 = new ConcreteReceiver("aaaa");
Command* cmd0 = new ConcreteCommand(recv0);
inv->addCommand(cmd0);
Receiver* recv1 = new ConcreteReceiver("bbbbb");
Command* cmd1 = new ConcreteCommand(recv1);
inv->addCommand(cmd1);
inv->doCommand();
inv->unDoCommand();
delete cmd1;
cmd1 = NULL;
delete recv1;
recv1 = NULL;
delete cmd0;
cmd0 = NULL;
delete recv0;
recv0 = NULL;
delete inv;
inv = NULL;
return 0;
}