Observer mode. cpp: defines the entry point of the console application
1. The so-called observer mode is the same as standing guard. As long as the notification is received, the corresponding notification will be sent.
2. Applications include Message notification mechanisms such as windows and QT. In fact, the Message notification mechanism is also the observer mode.
3. Example: in A company, there is A boss A, and then the company's employees go to work. Some of them watch the NBA, some stock trading, and one day the boss A suddenly becomes, then the Secretary sent A text message to the employees who watched the NBA and the stock. Then they handled it on their own.
4. Code:
// Observer mode. cpp: defines the entry point of the console application. // # Include "stdafx. h" # include
# Include
# Include
Using namespace std; // monitoring, observation, all have a base class, derived, to achieve different effects class Subject; // observer, must accept European messages, and process the message class Observer {protected: string name; // specify the name Subject * sub; // set who will notify me public: Observer (string name, Subject * sub ): name (name), sub (sub) {}virtual void update () = 0; // After receiving the message, I decided to handle it myself}; // supervisor class, manage all observers, add, delete, and send messages so that the observer can process class Subject {protected: list
Observers; public: string action; virtual void attach (Observer *) = 0; virtual void detach (Observer *) = 0; virtual void Policy () = 0; // notification Observer}; class StackObserver: public Observer {public: StackObserver (string name, Subject * sub): Observer (name, sub) {} void update ();}; void StackObserver: update () {cout <name <"received information" <sub-> action <endl; if (sub-> action = "") {cout <"leader coming in, I will close stack" <endl ;}} class NBAObserver: public Observer {public: NBAObserver (string name, Subject * sub ): observer (name, sub) {} void update () ;}; void NBAObserver: update () {cout <name <"Message received" <sub-> action <endl; if (sub-> action = "") {cout <"leader coming in, I will close NBA" <endl ;}} class Secretary: public Subject {public: void attach (Observer * observer) {observers. push_back (observer);} void detach (Observer * observer) {list
: Iterator itr = observers. begin (); while (itr! = Observers. end () {if (* itr) = observer) {observers. erase (itr) ;}itr ++ ;}} void Policy () {list
: Iterator iter = observers. begin (); while (iter! = Observers. end () {(* iter)-> update (); iter ++ ;}}; int _ tmain (int argc, _ TCHAR * argv []) {Subject * dwq = new Secretary (); Observer * nba = new NBAObserver ("NBAER", dwq); Observer * stack = new NBAObserver ("STACKER", dwq ); dwq-> attach (nba); dwq-> attach (stack); dwq-> action = "hava lanch"; dwq-> Y (); cout <endl; dwq-> action = "A"; dwq-> Y (); cin. get (); return 0 ;}