c++コマンドモード(command)
6763 ワード
コマンドモードのポイント:
1.コマンドキューを容易に設計することができる.
2.必要に応じて、コマンドをログに容易に記入できます.
3.要求の取り消しとやり直しを容易に実現できる.
4.新しい具体的なコマンドクラスを追加しても他のクラスには影響しないので、新しい具体的なコマンドクラスを追加するのは簡単です.
主関数:
1.コマンドキューを容易に設計することができる.
2.必要に応じて、コマンドをログに容易に記入できます.
3.要求の取り消しとやり直しを容易に実現できる.
4.新しい具体的なコマンドクラスを追加しても他のクラスには影響しないので、新しい具体的なコマンドクラスを追加するのは簡単です.
#include <iostream>
#include <vector>
using namespace std;
class Reciever
{
public:
void Action()
{
cout << "Do action !!" <<endl;
}
};
class Icommand
{
public:
virtual ~Icommand() {}
virtual void Excute() = 0;
protected:
Icommand() {}
};
class Read_Command:public Icommand
{
public:
Read_Command(Reciever *rev):m_rev(rev)
{
}
virtual void Excute()
{
cout << "Read Command.." << endl;
m_rev->Action();
}
~Read_Command()
{
}
private:
Reciever *m_rev;
};
class Write_Command:public Icommand
{
public:
Write_Command(Reciever *rev):m_rev(rev)
{
}
virtual void Excute()
{
cout << "Read Command.." << endl;
m_rev->Action();
}
~Write_Command()
{
}
private:
Reciever *m_rev;
};
class Invoker
{
public:
Invoker(Icommand* cmd):m_cmd(cmd)
{
}
Invoker()
{
}
~Invoker()
{
delete m_cmd;
}
void Notify()
{
std::vector<Icommand*>::iterator it = cmdList.begin();
for(it;it != cmdList.end();++it)
{
m_cmd = *it;
m_cmd->Excute();
}
}
void AddCmd(Icommand* pcmd)
{
cmdList.push_back(pcmd);
}
void DelCmd(Icommand* pcmd)
{
//cmdList.pop_back();
}
private:
Icommand* m_cmd;
std::vector<Icommand*> cmdList;
};
主関数:
#include <iostream>
#include <vector>
#include "command.h"
using namespace std;
int main()
{
Reciever* rev = new Reciever();
Icommand* cmd1 = new Read_Command(rev);
Icommand* cmd2 = new Write_Command(rev);
Invoker inv;
inv.AddCmd(cmd1);
inv.AddCmd(cmd2);
inv.Notify();
system("pause");
return 0;
}