命令模式的作用是将函数转换为对象,将实际的操作与并行的框架分离,命令模式属于行为级
类图如下:
代码来源于c++编程思想
class Task {
public:
virtual void operation() = 0;
};
class TaskRunner { //singleton pattern
static vector<Task*> tasks;
TaskRunner() {}
TaskRunner& operator=(TaskRunner&);
TaskRunner(const TaskRunner&);
static TaskRunner tr;
public:
static void add(Task& t) { tasks.push_back(&t); }
static void run() {
vector<Task*>::iterator it = tasks.begin();
while (it != tasks.end())
(*it++)->operation();
}
};
TaskRunner TaskRunner::tr; //init static member (non-int)
vector<Task*> TaskRunner::tasks;
class EventSimulator {
clock_t creation;
clock_t delay;
public:
EventSimulator() : creation(clock()) {
delay = CLOCKS_PER_SEC/4 * (rand()%20 + 1);
cout << "delay = " << delay << endl;
}
bool fired() {
return clock() > creation + delay;
}
};
class Button {
bool pressed;
string id;
EventSimulator e;
public:
Button(string name) : id(name), pressed(false) {}
void press() { pressed = true; }
bool isPressed() {
if (e.fired()) press();
return pressed;
}
friend ostream&
operator<<(ostream& os, const Button& b) {
return os << b.id;
}
};
class CheckButton : public Task {
bool handled;
Button button;
public:
CheckButton(Button& b) : button(b), handled(false) {}
void operation() {
if (!handled && button.isPressed()) {
cout << button << "pressed" << endl;
handled = true;
}
}
};
void procedure() {
TaskRunner::run();
}
void CommandPatternTest()
{
srand(time(0));
Button b1("B1"), b2("B2"), b3("B3");
CheckButton cb1(b1), cb2(b2), cb3(b3);
TaskRunner::add(cb1);
TaskRunner::add(cb2);
TaskRunner::add(cb3);
while (true)
{
procedure();
}
}