在发送者类与接收者类发送消息以及接受消息之间,可能并不能直接进行对话,或者说发送者不关系接收者是谁,而接收者也不需要发送者是谁。这样的一个关系特别像一个老板说,我不关系你怎么做,我只关系这件事的能不能成功。老板只负责发送命令,而并不关系过程,只关心结果。因此,这样的一个运行机制可以通过命令模式进行实现
1. Reciver类的编写
class Reciver{
public:
void action(){
cout << "reciver接受到了命令";
}
};
2. Command接口的编写
class Command{
public:
Command(){};
virtual void call() = 0;
};
class ConcerteCommand:public Command{
private:
Reciver* reciver;
public:
ConcerteCommand(){};
ConcerteCommand(Reciver* reciver):reciver(reciver){};
void call(){
if(!reciver){
reciver = new Reciver();
}
reciver->action();
}
};
3. Sender类的编写
class Sender{
private:
Command* command;
public:
Sender():command(nullptr){};
Sender(Command* command):command(command){};
void send(){
if(!command){
command = new ConcerteCommand();
}
cout << "Sender发送了命令" << endl;
command->call();
}
};
4. 主函数测试
int main(){
Reciver* revier = new Reciver();
ConcerteCommand* command = new ConcerteCommand(revier);
Sender* sender = new Sender(command);
sender->send();
return 0;
}