Design patterns that's something-observer mode

Source: Internet
Author: User

To put it simply, the pattern has only two roles, the Observer object (the subject) and the Observer object (the observer). Subject to receive the observer, there is an update to inform the observed person. We add two abstract interfaces respectively to the target of high cohesion and low coupling based on the dependency reversal principle.

Concept:
Observer mode (Observer), also known as publish \ Subscribe mode (publish\subscribe). It defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. This subject object notifies all observer objects when the state changes, enabling them to automatically update themselves.

Example:
A vivid and simple example always makes it easy to understand obscure concepts. Let's take a look at an example of a replacement for a car part.
You should have heard of it. Toyota Depot in Japan has previously announced the recovery of more than 9 million private cars and lorries in the United States, Europe and China, as well as replacement parts, as a result of the accelerator pedal problem. This incident has undoubtedly caused a major blow to the Toyota brand.
Assuming that the Toyota accelerator pedal manufacturers and Bmw,ferrali and Benz, when the accelerator pedal problems, the accelerator pedal manufacturers will issue a formal part change notice, all the brands of cars will receive the same update notice: Replace the accelerator pedal parts to ensure the safety of the user's use of the vehicle.
As can be seen, the accelerator pedal manufacturers issued notification updates, all car suppliers will be notified and updated, is the Observer mode.

role:
To put it simply, the pattern has only two roles, the Observer object (the subject) and the Observer object (the observer). Subject to receive the observer, there is an update to inform the observed person. We add two abstract interfaces respectively to the target of high cohesion and low coupling based on the dependency reversal principle.
1. Abstract theme (Subject): It saves all references to the Observer object in a single aggregation, each subject can have any number of observers. Abstract topics provide an interface that can add and remove observer objects;
2. Specific theme (ConcreteSubject): deposit the relevant state into the specific observer object, and notify all registered observers when the internal state of the specific subject changes. This can refer to the accelerator pedal manufacturer;
3. Abstract Observer (Observer): Define an interface for all the specific observers and update themselves when the subject is notified;
4. Specific observer (Concreteobserver): Implements the update interface required by the abstract observer role in order to reconcile the state of itself with the state of the topic. This can refer to Bmw,ferrali and Benz.

UML diagram:

Code:

#pragma warning (disable:4786)#include <iostream>#include <vector>#include <list>#include <string>using namespace STD;//Specific observer structuretypedef structobserveritems{stringStrName; Observer* Pobserver;} Observersets;//Abstract observerclassobserver{ Public:Virtual voidUpdate () =0;};//Abstract notifierclassnotice{ Public:Virtual voidAddobserver (observersets* ob) =0;Virtual voidRemoveobserver (observersets* ob) =0;Virtual voidNotify () =0;};//Specific notifying personclassConcretenotice: Publicnotice{ Public:Virtual~concretenotice () { list<ObserverSets*>:: 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:stringGetState () {returnM_noticestate; }voidSetState (stringstrstate) {m_noticestate = strstate; } Public://Increase the viewer    voidAddobserver (observersets* ob) {observers.push_back (OB); }//Remove observer    voidRemoveobserver (observersets* ob) { list<ObserverSets*>:: Iterator Stiter; for(Stiter=observers.begin (); Stiter!=observers.end ();) {if((*stiter)->strname==ob->strname) {observers.erase (stiter); Break; }Else{++stiter; }        }    }//Notification update    voidNotify () { list<ObserverSets*>:: Iterator Stiter; for(Stiter=observers.begin (); Stiter!=observers.end (); stiter++)        {(*stiter)->pobserver->update (); }    }Private:stringM_noticestate; list<ObserverSets*>Observers;};//Specific observerclassConcreteobserver: Publicobserver{ Public: Concreteobserver (concretenotice* notice,stringName) { This->m_notice = Notice; This->m_strname = name; }voidUpdate () {m_strobserverstate = M_notice->getstate ();cout<<"NOTICE:"<<m_strName<<"to replace:"<<m_strObserverState<<endl; }Private:stringM_strname;stringM_strobserverstate; Concretenotice* M_notice;};voidMain () {concretenotice* notice =NewConcretenotice; observersets* Pobitem =NewObserversets; observer* Pob=null;//Add BMW car WatcherPOb =NewConcreteobserver (Notice,"BMW Car");    Pobitem->pobserver = pOb; Pobitem->strname ="BMW Car"; Notice->addobserver (Pobitem);//Add Ferrali car WatcherPobitem =NewObserversets; POb =NewConcreteobserver (Notice,"Ferrali Car");    Pobitem->pobserver = pOb; Pobitem->strname ="Ferrali Car"; Notice->addobserver (Pobitem);//Add Benz Car WatcherPobitem =NewObserversets; POb =NewConcreteobserver (Notice,"Benz Car");    Pobitem->pobserver = pOb; Pobitem->strname ="Benz Car"; Notice->addobserver (Pobitem);//removal of Benz car watcherNotice->removeobserver (Pobitem); Notice->setstate ("Tires"); Notice->notify ();DeleteNotice notice = NULL;return;}

divergence:
We know there are three ways to implement C + + polymorphism: function overloading, template functions, and virtual functions. virtual function Implementation of polymorphism called Dynamic polymorphism, the above code has the following characteristics:
1. The object of the subclass is converted to the object of the parent class, which we call an upward transformation. It is secure, auto-completed, and will lose the subtype of information;
2. In order to solve the problem that the subtype information is lost (the subclass object is converted to the parent class), the parent class must implement a virtual function;
3. Subclasses have exactly the same functions, overriding the virtual functions that override the parent class, so that dynamic polymorphism can be achieved (otherwise, pointers or references only).

Application Scenarios:
1. When an object changes, other objects need to be changed, and it is not possible to know how many objects remain to be changed;
2. Objects only need to notify their own updates to other objects without needing to know the details of other objects.

Advantages:
1. Subject when sending the broadcast notice, do not need to specify the specific observer,observer can decide whether to subscribe subject notice;
2. High cohesion, low coupling, can be independently changed.

defects:
1. Loose coupling causes the code relation to be not obvious, sometimes may be difficult to understand;
2. If a subject is subscribed by a large number of observer, there may be an efficiency issue when broadcasting a notification.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Design patterns that's something-observer mode

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.