Design Pattern-Observer Pattern

Source: Internet
Author: User

Design Pattern-Observer Pattern

To put it simply, this mode has only two types of roles: the observer object (topic) and the observer object (observer ). When a topic is received by the observer, an update notification is sent to the observer. Based on the Dependency inversion principle, we add two abstract interfaces for High Cohesion and low coupling.

Concept:
Observer, also known as PublishSubscribe ). It 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.

Example:
A fresh and simple example can make it easy to understand obscure concepts. Let's take a look at an example of car parts replacement.
You should have heard of it. Japan's Toyota car factory previously announced the recycling of more than million private cars and trucks in the United States, Europe and China due to the accelerator pedal problem, replace parts. This event has undoubtedly caused a major blow to the Toyota brand.
Assume that the manufacturer of the Toyota accelerator pedal is the same as that of BMW, Ferrali, and Benz. When there is a problem with the accelerator pedal, the accelerator pedal manufacturer will issue a formal notice of part replacement, all of the above brands of cars will receive the same update notification: Change the accelerator pedal parts to ensure the safety of the user's use of vehicles.
The above shows that when the accelerator pedal manufacturer sends a notification update, all automotive suppliers will receive the notification and update it, which is the observer mode.

Role:
To put it simply, this mode has only two types of roles: the observer object (topic) and the observer object (observer ). When a topic is received by the observer, an update notification is sent to the observer. Based on the Dependency inversion principle, we add two abstract interfaces for High Cohesion and low coupling.
1. Abstract topic: It stores all references to the observer object in a collection, and each topic can have any number of observers. Abstract topic provides an interface for adding and deleting observer objects;
2. ConcreteSubject: stores the status in a specific observer object, and sends a notification to all registered observers when the internal status of the subject changes. The accelerator pedal manufacturer can be referred to here;
3. Abstract Observer: defines an interface for all specific observers and updates themselves when receiving notifications of the topic;
4. ConcreteObserver: implements the update interface required by the abstract observer role to coordinate its status with the topic status. This can be BMW, Ferrali, and Benz.

UML diagram:

Code:

# Pragma warning (disable: 4786) # include
  
   
# Include
   
    
# Include
    
     
# Include
     
      
Using namespace std; // Type Def struct ObserverItems {string strName; Observer * pObserver;} ObserverSets; // abstract Observer class Observer {public: virtual void Update () = 0 ;}; // abstract notifier class Notice {public: virtual void AddObserver (ObserverSets * ob) = 0; virtual void RemoveObserver (ObserverSets * ob) = 0; virtual void required y () = 0 ;}; // The class ConcreteNotice: public Notice {public: virtual ~ ConcreteNotice () {list
      
        : Iterator stIter; for (stIter = observers. begin (); stIter! = Observers. end (); stIter ++) {if (* stIter)-> pObserver! = NULL) {delete (* stIter)-> pObserver; (* stIter)-> pObserver = NULL;} if (* stIter )! = NULL) {delete (* stIter); (* stIter) = NULL ;}} public: string getState () {return m_noticeState;} void setState (string strState) {m_noticeState = strState;} public: // Add the observer void AddObserver (ObserverSets * ob) {observers. push_back (ob);} // remove the observer void RemoveObserver (ObserverSets * ob) {list
       
         : Iterator stIter; for (stIter = observers. begin (); stIter! = Observers. end ();) {if (* stIter)-> strName = ob-> strName) {observers. erase (stIter); break;} else {++ stIter ;}}// Notify void Notify () {list
        
          : Iterator stIter; for (stIter = observers. begin (); stIter! = Observers. end (); stIter ++) {(* stIter)-> pObserver-> Update () ;}} private: string m_noticeState; list
         
           Observers;}; // The class ConcreteObserver: public Observer {public: ConcreteObserver (ConcreteNotice * notice, string name) {this-> m_Notice = notice; this-> m_strName = name;} void Update () {m_strObserverState = m_Notice-> getState (); cout <notification: <
          
            PObserver = pOb; pObItem-> strName = BMW car; notice-> AddObserver (pObItem); // Add the Ferrali car observer pObItem = new ObserverSets; pOb = new ConcreteObserver (notice, ferrali car); pObItem-> pObserver = pOb; pObItem-> strName = Ferrali car; notice-> AddObserver (pObItem); // Add the Benz car observer pObItem = new obsets; pOb = new ConcreteObserver (notice, Benz car); pObItem-> pObserver = pOb; pObItem-> strName = Benz car; notice-> AddObserver (pObItem ); // remove Benz car observer notice-> RemoveObserver (pObItem); notice-> setState (tire); notice-> require y (); delete notice; notice = NULL; return ;}
          
         
        
       
      
     
    
   
  

Divergence:
We know that there are three methods to realize C ++ polymorphism: function overload, template function, and virtual function. The polymorphism implemented by virtual functions is called dynamic polymorphism. The above Code has the following features:
1. The subclass object is converted to the parent class object, which is called upward transformation. It is secure and automatically completed, and information of child types will be lost;
2. To solve the problem of child type information loss (subclass object is converted to parent class), the parent class must implement a virtual function;
3. The subclass has identical functions that overwrite the virtual functions of the parent class, so that dynamic polymorphism can be realized (otherwise, only pointers or references can be used ).

Application scenarios:
1. When an object changes, other objects need to be changed at the same time, and you may not know how many objects need to be changed;
2. The object only needs to notify other objects of its own updates without knowing the details of other objects.

Advantages:
1. When a Subject sends a broadcast notification, it does not need to specify a specific Observer. The Observer can decide whether to subscribe to the Subject notification;
2. High Cohesion and low coupling, which can be changed independently.

Defects:
1. the loose coupling may make the code relationship less obvious and sometimes hard to understand;
2. If a Subject is subscribed to by a large number of Observer users, it may be efficient during broadcast notifications.

 

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.