[Design mode] design mode: Observer mode (observerpattern) implemented by C ++ Programming)

Source: Internet
Author: User
Observer mode definition: Defines one-to-multiple dependencies between objects. In this way, when an object changes its state, all dependent objects will be notified and automatically updated.
The observer mode is also called the publish/subscribe mode, Model-View Mode, source-listener mode, or dependents mode) mode.

The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.

Class Diagram
Figure 1 Observer pattern class diagram
We can see that in the implementation of this observer mode, there are the following roles:

  1. Abstract topic role: The topic role stores all references to the observed objects in one aggregation. Each topic can have any number of observers. An abstract topic provides an interface to add and delete observer objects. A Topic role is also called an abstract observer role. It is generally implemented using an abstract class or an interface.
  2. Abstract observer (observer) Role: Defines an interface for all the specific observers and updates themselves when receiving notifications of the topic. This interface is called the update interface. Abstract observer roles are generally implemented using an abstract class or an interface. In this schematic implementation, the update Interface contains only one method (that is, the update () method). This method is called the update method.
  3. Concretesubject role: Stores the relevant status to a specific observer object. When the internal status of a specific topic changes, a notification is sent to all registered observers. A topic role is also called a concrete observable ). A topic role is usually implemented by a specific subclass.
  4. Concreteobserver role: The storage status is the same as that of the topic. The observer role implements the update interface required by the abstract observer role, so that the state of the observer can be consistent with the state of the topic. If necessary, the observer role can save a reference pointing to a specific topic object. A specific observer role is usually implemented by a specific subclass.

The observer mode provides an object design that allows loose coupling between the subject and the observer. When two objects are loosely coupled, they can still interact, but they are not very clear about each other's details.
The topic only knows that the observer has implemented an interface (observer ). The topic does not need to know who the observer is, what it has done, or any other details. We can add new observers at any time. The only thing that a topic depends on is a list of objects that implement the observer interface. When a new type of observer appears, the topic'sCodeNo need to modify. All you need to do is implement the observer interface in the new class and register as the observer. Changing the subject or one of the observers does not affect the other. Because the two are loosely coupled.
Meteorological Station instance c ++ programming implementation
(From head first design model): Class diagram:
Code:
// Observer Mode C ++ programming implementation // Author: Jiangnan smoke rain // E-mail: xiajunhust@gmail.com # include <iostream> # include <vector> # include <algorithm> using namespace STD; static int setconditiontimes = 0; // record the total number of times set // observer (billboard) abstract Interface Class observer {public: Virtual void Update (float temp, float humidity, Float Pressure) = 0 ;}; // topic abstract interface class subject {public: virtual void registerobserver (Observer * o) = 0; // register the virtual void removeobserver (Observer * o) = 0; // Delete the observer virtual void notifyobserver () = 0; // notify all observers when the topic status changes.}; // The notification board displays class displayelement {public: virtual void display () = 0 ;}; // The specific weatherdata class, inherited from the topic abstract class weatherdata: public subject {PRIVATE: vector <Observer *> observers; float temperature; float humility; Float Pressure; public: weatherdata (){}~ Weatherdata () {vector <Observer *>: iterator Pos = observers. Begin (); For (; pos! = Observers. end (); ++ POS) {Delete (* POS) ;}} void registerobserver (Observer * o) {observers. push_back (o);} void removeobserver (Observer * o) {vector <Observer *>: iterator Pos = find (observers. begin (), observers. end (), O); If (Pos! = Observers. end () {observers. erase (POS) ;}} void policyobserver () {vector <Observer * >:: iterator Pos = observers. begin (); For (; pos! = Observers. end (); ++ POS) {(* POS)-> Update (temperature, humility, pressure) ;}// when an updated observation value is obtained from a weather station, notification observer void messurementschanged () {policyobserver ();} // set the void setmessurements (float temperature, float humility, Float Pressure) {++ setconditiontimes; this-> temperature = temperature; this-> humility = humility; this-> pressure = pressure; messurementschanged () ;}}; // notice board specific class: current status class currentconditiondisplay: public obs Erver, public displayelement {PRIVATE: float temperature; float humility; Subject * weatherdata; public: currentconditiondisplay (subject * weatherdata) {This-> weatherdata = weatherdata; weatherdata-> registerobserver (this );}~ Currentconditiondisplay () {} void Update (float temp, float humi, Float Pressure) {This-> temperature = temp; this-> humility = humi; display ();} void display () {cout <"current conditions:" <temperature <"f degrees and" 

Running result (vs2008 + win7 ):

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.