ESP-IDF:命令模式
/命令模式/
/设计模式之开闭原则,对增加开放对修改关闭/
#include
#include
class ClientCommands{ //统一管理命令,这是比观察者模式多出来的地方
public:
void AddMoney(){
cout<<“add money”<<endl;
}
void AddEquipment(){
cout<<“add equipment”<<endl;
}
void AddFriend(){
cout<<“add friend”<<endl;
}
};
class AbstractCommand {
public:
virtual void handle() = 0; //纯虚函数,子类必须实现,此函数实现多态:父类指针指向子类方法,根据子类对象调用子类方法
};
class AddMoney:public AbstractCommand {
public:
AddMoney(ClientCommands * commandmy) {
this->commandmy=commandmy;
}
virtual void handle() {
this->commandmy->AddMoney();
}
public:
ClientCommands * commandmy;
};
class AddEquipment:public AbstractCommand {
public:
AddEquipment(ClientCommands * commandmy) {
this->commandmy=commandmy;
}
virtual void handle() {
this->commandmy->AddEquipment();
}
public:
ClientCommands * commandmy;
};
class AddFriend:public AbstractCommand {
public:
AddFriend(ClientCommands * commandmy) {
this->commandmy=commandmy;
}
virtual void handle() {
this->commandmy->AddFriend();
}
public:
ClientCommands * commandmy;
};
// class Server21 {
// public:
// void increaseCommand(AbstractCommand * command) {
// myStack.push(command);
// }
// void handlecommand() {
// while(myStack.size()>0) {
// AbstractCommand * command = myStack.top();
// command->handle();//父类指针指向子类方法,根据子类对象调用子类方法,从而实现多态
// myStack.pop();
// }
// cout<<“Have finish all command”<<endl;
// }
// public:
// stack<AbstractCommand *> myStack;
// };
class Server21 {
public:
void increaseCommand(AbstractCommand * command) {
myQueue.push(command);
}
void handlecommand() {
while(myQueue.size()>0) {
AbstractCommand * command = myQueue.front();
command->handle();//父类指针指向子类方法,根据子类对象调用子类方法,从而实现多态
myQueue.pop();
}
cout<<“Have finish all command”<<endl;
}
public:
queue<AbstractCommand *> myQueue;
};
void test21() {
Server21 servermy;
ClientCommands * clientcommand = new ClientCommands;
AbstractCommand * absCommandAddmoney = new AddMoney(clientcommand);//定义父类指针指向子类对象
AbstractCommand * absCommandAddEquipment = new AddEquipment(clientcommand);//定义父类指针指向子类对象
AbstractCommand * absCommandAddFriend = new AddFriend(clientcommand);//定义父类指针指向子类对象
servermy.increaseCommand(absCommandAddmoney);
servermy.increaseCommand(absCommandAddEquipment);
servermy.increaseCommand(absCommandAddFriend);
cout<<“--------test 命令方法模式----------”<<endl;
servermy.handlecommand();
free(absCommandAddmoney);
free(absCommandAddEquipment);
free(absCommandAddFriend);
free(clientcommand);
}
extern “C” void app_main(void)
{
test21();
}