// MT2Q4.cpp #include #include struct ICommand { virtual void execute() = 0; }; class invoker { public: void invoke() { for(size_t i=0; iexecute(); } static void Register(ICommand* pCommand) { commands.push_back(pCommand); } private: static std::vector commands; }; std::vector invoker::commands; void scope1() { static bool eventHappened = false; static bool firstPass = true; class comm1 : public ICommand { void execute() { eventHappened = true; } }; if(firstPass) { firstPass = false; invoker inv1; inv1.Register(new comm1); } if(eventHappened) std::cout << "\n event recorded in scope1"; else std::cout << "\n no event yet in scope1"; } void scope2() { static bool eventHappened = false; static bool firstPass = true; class comm2 : public ICommand { void execute() { eventHappened = true; } }; if(firstPass) { firstPass = false; invoker inv2; inv2.Register(new comm2); } if(eventHappened) std::cout << "\n event recorded in scope2"; else std::cout << "\n no event yet in scope2"; } void main() { invoker inv; for(int i=0; i<6; ++i) { if(i==3) inv.invoke(); // event happened scope1(); scope2(); } }