- Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
- Promote “invocation of a method on an object” to full object status
- An object-oriented callback
1.Create a class that encapsulates some number of the following:
- A “receiver” object
- The method to invoke
- The arguments to pass
2.Instantiate an object for each “callback”
3.When the sender is ready to callback to the receiver, it calls execute()
#include <vector>
#include <algorithm>
#include <iostream>
class CCommandPattern
{
public:
virtual ~CCommandPattern() {
}
virtual void m_execute()=0;
};
class CDisplayHello : public CCommandPattern
{
public:
void m_execute() {
std::cout << "Hello ";
}
};
class CDisplayWorld : public CCommandPattern
{
public:
void m_execute(){
std::cout << "world!" << std::endl;
}
};
class Commands
{
private:
std::vector<CCommandPattern*> commands;
struct ExecuteCommand {
void operator()(CCommandPattern * cmd) {
cmd->m_execute();
}
};
public:
void add_command(CCommandPattern & cmd){
commands.push_back(&cmd);
}
void m_execute() {
std::for_each(commands.begin(), commands.end(), ExecuteCommand());
}
};
void HelloWorld(Commands & commands) {
commands.m_execute();
}
int main(){
Commands commands;
CDisplayHello hello;
CDisplayWorld world;
commands.add_command(hello);
commands.add_command(world);
HelloWorld(commands);
return 0;
}