#include<iostream>
#include<vector>
using namespace std;
#include<vector>
using namespace std;
// 先定义一个Command的基类
class Command
{
public:
virtual ~Command()
{
}
virtual void Execute() = 0;
protected:
Command()
{
}
};
// 为了能执行多个类的符合某个函数声明的成员函数,这里有个二个变化的点,一个是哪个类? 这个成员函数的函数原型是什么样的。
class Command
{
public:
virtual ~Command()
{
}
virtual void Execute() = 0;
protected:
Command()
{
}
};
// 为了能执行多个类的符合某个函数声明的成员函数,这里有个二个变化的点,一个是哪个类? 这个成员函数的函数原型是什么样的。
// 可以分别用模板和成员函数指针来实现。特定类型的对象,以及该对象的成员函数可以一起构造一个Command
template<class Receiver>
class SimpleCommand : public Command
{
public:
typedef void (Receiver::*Action)();
SimpleCommand(Receiver* r, Action a) : _receiver(r),_action(a)
{
}
virtual void Execute()
{
(_receiver->*_action)();
}
private:
Action _action;
Receiver* _receiver;
};
class MyClass
{
public:
void redo()
{
cout << "in myclass" << endl;
}
};
class YourClass
{
public:
void check()
{
cout << "check your class" << endl;
}
};
int main(int argc, char** argv)
{
MyClass* receiver = new MyClass;
Command* aCommand = new SimpleCommand<MyClass>(receiver,&MyClass::redo);
YourClass* youReceiver = new YourClass;
Command* yCommand = new SimpleCommand<YourClass>(youReceiver,&YourClass::check);
vector<Command*> commandQueue;
commandQueue.push_back(aCommand);
commandQueue.push_back(yCommand);
for(int i = 0 ; i < commandQueue.size(); i++)
{
commandQueue[i]->Execute();
}
}