#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <QCoreApplication>
using namespace std;
class AbstractReceiver{
public:
virtual void ExcuteCommand() = 0;
virtual ~AbstractReceiver(){}
};
class AbstractCommand{
public:
virtual void ExcuteCommand() = 0;
virtual ~AbstractCommand(){}
};
class ConcreteCommandOne:public AbstractCommand{
public:
explicit ConcreteCommandOne(AbstractReceiver *receiver):m_pReceiver(receiver){}
void ExcuteCommand()
{
m_pReceiver->ExcuteCommand();
cout << "command is One" << endl;
}
protected:
AbstractReceiver* m_pReceiver;
};
class ConcreteCommandTwo:public AbstractCommand{
public:
explicit ConcreteCommandTwo(AbstractReceiver *receiver):m_pReceiver(receiver){}
void ExcuteCommand()
{
m_pReceiver->ExcuteCommand();
cout << "command is two" << endl;
}
protected:
AbstractReceiver* m_pReceiver;
};
class ConcreteReceiverOne:public AbstractReceiver{
public:
void ExcuteCommand()
{
cout << "ConcreteReceiverOne excute command" << endl;
}
};
class Invoker{
public:
void SetCommand(AbstractCommand* command)
{
m_CommandList.push_back(command);
}
void RemoveCommand(AbstractCommand* command)
{
m_CommandList.remove(command);
}
void Notify()
{
foreach (auto command, m_CommandList)
{
command->ExcuteCommand();
}
}
private:
list<AbstractCommand *> m_CommandList;
};
int main(int argc,char** argv)
{
AbstractReceiver* receiver = new ConcreteReceiverOne();
AbstractCommand* command1 = new ConcreteCommandOne(receiver);
AbstractCommand* command2 = new ConcreteCommandTwo(receiver);
Invoker invoker;
invoker.SetCommand(command1);
invoker.SetCommand(command2);
invoker.Notify();
cout << "cancle command one" << endl;
invoker.RemoveCommand(command1);
invoker.Notify();
if(command1 != nullptr)
{
delete command1;
command1 = nullptr;
}
if(command2 != nullptr)
{
delete command2;
command2 = nullptr;
}
return 0;
}