命令模式:通过被称为Command 的类封装了对目标对象的调用行为以及调用参数。
在面向对象的程序设计中,一个对象调用另一个对象,一般情况下的调用过程是:创建目标对象实例;设置调用参数;调用目标对象的方法。但在有些情况下有必要使用一个专门的类对这种调用过程加以封装,我们把这种专门的类称作 command 类。
命令模式:是将一个请求封装为一个对象,从而使你可用不同的请求对客户端进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
class Doctor {
public:
void treat_Eye() {
cout << "doctor treat eye---------" << endl;
}
void treat_Nose() {
cout << "doctor treat nose---------" << endl;
}
};
class Command {
public:
virtual void treat() = 0;
};
class CommandTreatEye:public Command{
public:
CommandTreatEye(Doctor* doctor) {
m_doctor = doctor;
}
void treat() {
m_doctor->treat_Eye();
}
private:
Doctor* m_doctor;
};
class CommandTreatNose :public Command {
public:
CommandTreatNose(Doctor* doctor) {
m_doctor = doctor;
}
void treat() {
m_doctor->treat_Nose();
}
private:
Doctor* m_doctor;
};
class Nurse {
public:
Nurse(Command* com) {
m_command = com;
}
void submittedCase() {
m_command->treat();
}
private:
Command* m_command;
};
class AdvNurse {
public:
AdvNurse() {
m_list.clear();
}
void setCommand(Command* com) {
m_list.push_back(com);
}
void submittedCase() {
list<Command*>::iterator it;
for (it = m_list.begin(); it != m_list.end(); it++) {
(*it)->treat();
}
}
private:
list<Command*> m_list;
};
void testMethod1() {
Doctor* doc = new Doctor;
Command* com = new CommandTreatEye(doc);
com->treat();
delete com;
delete doc;
}
void testMethod2() {
Doctor* doc = new Doctor;
Command* com = new CommandTreatEye(doc);
Nurse* nurse = new Nurse(com);
nurse->submittedCase();
delete nurse;
delete com;
delete doc;
}
void testMethod3() {
Doctor* doc = new Doctor;
Command* com1 = new CommandTreatEye(doc);
Command* com2 = new CommandTreatNose(doc);
AdvNurse* anurse = new AdvNurse();
anurse->setCommand(com1);
anurse->setCommand(com2);
anurse->submittedCase();
delete anurse;
delete com2;
delete com1;
delete doc;
}
int main()
{
//testMethod1();
//testMethod2();
testMethod3();
system("pause");
return 0;
}