Observer mode in design mode (C ++ implementation)

Source: Internet
Author: User

The observer mode (observer) defines one-to-multiple relationships between objects. When the State of an object changes, all the observer objects associated with it will be notified. The observer mode decouples the observed target from the observer. A target can have any number of observers, and the observer can observe any number of goals to form a complex association, each observer does not know the existence of other observers.

 

Here I will not list so many formal UML diagrams. Those are books. If you want to learn the design pattern in detail, we recommend the gof big talk design pattern.

 

Here are two examples to illustrate

First, when the water bottle is hot, when it reaches 97 degrees, the display will receive a message, and then the current temperature is displayed on the screen, the sound controller will sound, prompting an alarm!

Second: a software company suddenly came to a sexy female secretary. Programmers A and programmers B couldn't afford the two fishing lines. They watched the female secretary closely, and every move of the Secretary would affect them!

 

Let's take a look at the first question. After a careful analysis, most people will write the following code:

Class heater {PRIVATE: signed int temperature; public: // void boilwater () {for (INT I = 0; I <= 100; ++ I) {temperature = I; If (temperature = 97) {showmsg (); makealert () ;}}// void showmsg () displayed on the display () {cout <"who is about to open, current temperature:" <temperature <", don't burn it again" <Endl ;}// the alarm void makealert () {cout <"alarm: Tick, water already" <temperature <"" <Endl ;}};

Although such a design can achieve the goal, it is not a good method. We know that the water heater, display screen and alarm may not be produced by the same manufacturer, so we should divide them into several categories, the Code is as follows:

 

// Burner (observed) Class heater {PRIVATE: signed int temperature; public: // void boilwater () {for (INT I = 0; I <= 100; ++ I) {temperature = I; If (temperature = 97) {// send information to the two classes that listen to him }}}; // display class (observed) class show {public: void showmsg (int param) {cout <"who is about to open, current temperature:" <Param <", stop burning "<Endl ;}; // alert class (observed) Class alarm {public: void makealert (int param) {cout <" alarm: Tick, the water has been "<temperature <" "<Endl ;}}

Like the above design, both the display and alarm classes are monitoring the temperature of the heater. When the temperature reaches 97 degrees, the burner will send messages like the two of them, while executing the necessary operations, C ++ does not have delegate and event processing like C #. Therefore, polymorphism is required in C ++ and vector is used for message processing, I believe this example has already clearly described the observer mode. Next let's implement the second example.

 

 

The example structure is as follows:

Iobservable, observer Interface

Cmishuobservable, Secretary of the observer

Iobserver, observer Interface

Ccoderbobserver, observer programmer B

Ccoderaobserver observer programmer

Class iobservable // observer interface {iobservable () {} virtual ~ Iobservable () {} virtual void addobserver (iobserver * pobserver) = 0; // all operations performed by the observer on virtual void deleteobserver (iobserver * pobserver) = 0; virtual void policyobservers (string context) = 0 ;}; class cmishuobservable: Public iobservable // The delegate inherits and implements the interface function {PRIVATE: vector <iobserver *> m_observerlist; // The typedef vector container used to hold the observer <iobserver *>: iterator observer_iter; public: Virtual void addobserver (iobserver * Pobserver) {m_observerlist.push_back (pobserver); // Add the observer to the container} virtual void deleteobserver (iobserver * pobserver) // Delete and observe {observer_iter it = m_observerlist.begin (); for (; it! = M_observerlist.end (); ++ it) {If (pobserver = * It) // This is a bit difficult to handle. It shouldn't be a pointer. For example, use m_observerlist.erase (IT );}} virtual void policyobservers (string context) // notify the observer to execute the update {observer_iter it = m_observerlist.begin (); For (; it! = M_observerlist.end (); ++ it) (* It)-> Update (context);} void havebreakfast () // delegate behavior {cout <"Beauty Secretary: start to eat, ELE. Me "<Endl; this-> yyobservers (string (" start to eat, ELE. Me ");} void havefun () // delegate behavior {cout <"Beauty SECRETARY: people really want to play! "<Endl; this-> policyobservers (string (" someone else wants to play! ") ;}}; Class iobserver // observer interface {public: iobserver () {} virtual ~ Iobserver () {}; virtual void Update (string context) = 0 ;}; class ccoderaobserver: Public iobserver // programmer A inherits and implements update {PRIVATE: string name; public: ccoderaobserver () {name = "coder a";} virtual void Update (string context) {// receives the message: I really want to play, or go to dinner // execute the corresponding operation}; Class ccoderbobserver: Public iobserver // programmer B and implement update {PRIVATE: string name; public: ccoderbobserver () {name = "coder B";} virtual void Update (string context) {// receive the message: I really want to play, or go to dinner // execute the corresponding operation }};

 

 

 

The above example shows how to implement the observer mode in C ++. The summary is to use polymorphism + container to call the observer's update function separately!

 

 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.