Design Pattern --- Command
class ReceiverA { public: // Interface. void Action() { cout <<"ReceiverA::Action()." <<endl; } }; class ReceiverB { public: // Interface. void Action() { cout <<"ReceiverB::Action()." <<endl; } }; class Command { public: virtual ~Command(){} public: // Interface. virtual void Execute() = 0; }; class CommandA : public Command { // data. ReceiverA &m_receiver; public: CommandA(ReceiverA ra) : m_receiver(ra) {} public: // Interface. virtual void Execute() override { m_receiver.Action(); } }; class CommandB : public Command { // data. ReceiverB &m_receiver; public: CommandB(ReceiverB rb) : m_receiver(rb) {} public: // Interface. virtual void Execute() override { m_receiver.Action(); } }; int main(int argc, char *argv[]) { ReceiverA ra; ReceiverB rb; Command *ca = new CommandA(ra), *cb = new CommandB(rb); ca->Execute(); // 此时, 调用者无需区分执行的内容, 只需要调用 Execute 即可. cb->Execute(); // 此模式借助 Command 这个中间层, 在调用者 ('main' 函数) 和被调用者 ('ReceiverA' 和 'ReceiverB') 之间解耦. // TODO: Release memory. return 0; }