Observer pattern for Design patterns (c + +)

Source: Internet
Author: User

The Observer pattern should be one of the most widely used and most influential patterns, because an instance of Observer Model/view/control (MVC) structure has a very important position and significance in the design of system development architecture. MVC implements decoupling of business logic and presentation layer. In MFC, Doc/view (document view architecture) provides a framework for implementing MVC. In the Java lineup, Struts provides a framework for implementing MVC, similar to the Doc/view structure in MFC. In addition, the Java language itself provides an implementation interface for the Observer pattern. Of course, MVC is just an example of the Observer pattern. Observer mode to solve the problem is: the establishment of a (Subject) to many (Observer) of the dependency, and when the "one" change, rely on the "one" more can also be synchronized change.

In Gof's design model: The basics of reusable object-oriented software, the Observer pattern is said: Define a one-to-many dependency between objects, and when the state of an object changes, all objects that depend on it are notified and automatically updated. When an object changes, the objects that follow it are notified; This interaction is also known as a publish-subscribe (publish-subscribe). The target is the publisher of the notification, and it does not need to know who the observer is when it issues a notification.

one of the most common examples is when we are doing statistical analysis of the same set of data, we want to be able to provide many forms of representation (e.g., statistical display in tables, histogram statistics, percentage statistics, etc.). These representations all depend on the same set of data, and we certainly need to change all the statistics when the data is changed. The Observer model solves this problem.

UML Class Diagrams:

Subject (target)
--the target knows its observer. There can be any number of observers observing the same target;
--Provides an interface for registering and deleting observer objects.

OBSERVER (Observer)
--Define an update interface for objects that need to be notified when the target is changed.

ConcreteSubject (Specific target)
-Deposit the relevant state into the Concreteobserver object;
-When its state changes, give notice to its various observers.

Concreteobserver (Specific observer)
--Maintain a reference to the ConcreteSubject object;
-Storage of the state, which should be consistent with the state of the target;
--Implements the Observer update interface to align its state with the state of the target.

The Observer pattern collaborates in the following ways:

      1. When ConcreteSubject any change that could cause its observer to be inconsistent with its own state, it will notify its observers;
      2. The Concreteobserver object can query the target object for information after it has been notified of a change to a specific target. Concreteobserver uses this information to make its state consistent with the state of the target object.

Here is the call Timing diagram:

Applicable occasions

You can use the observer pattern in either of the following situations:

    1. When an abstract model has two facets, one aspect depends on the other. The two are encapsulated in separate objects so that they can be independently changed and reused;
    2. When changes to an object need to change other objects at the same time, it is not known how many objects remain to be changed;
    3. When an object must notify other objects, and it cannot assume that other objects are who, that is, you do not want these objects to be tightly coupled.

Code implementation:

#include <iostream> #include <list>using namespace std;class observer{public:virtual void Update (int) = 0;}; Class subject{public:virtual void Attach (Observer *) = 0;virtual void Detach (Observer *) = 0;virtual void Notify () = 0;}; Class Concreteobserver:public Observer{public:concreteobserver (Subject *psubject): M_psubject (psubject) {}void Update (int value) {cout << concreteobserver get the update. New state: "<< value << Endl;} Private:subject *m_psubject;}; Class Concreteobserver2:public Observer{public:concreteobserver2 (Subject *psubject): M_psubject (pSubject) {}void Update (int value) {cout << ConcreteObserver2 get the update. New state: "<< value << Endl;} Private:subject *m_psubject;}; Class Concretesubject:public subject{public:void Attach (Observer *pobserver); void Detach (Observer *pobserver); void Notify (); void SetState (int state) {m_istate = state;} Private:std::list<observer *> m_observerlist;int m_istate;}; void ConcreteSubject:: Attach (Observer *pobserver) {m_observerlist.push_back (pobserver);} void ConcreteSubject::D etach (Observer *pobserver) {m_observerlist.remove (pobserver);} void Concretesubject::notify () {std::list<observer *>::iterator it = M_observerlist.begin (); while (it! = m_ Observerlist.end ()) {(*it)->update (m_istate); ++it;}} int main () {//create subjectconcretesubject *psubject = new ConcreteSubject ();//create observerobserver *pobserver = new Concreteobserver (psubject); Observer *pobserver2 = new ConcreteObserver2 (psubject);//Change the statepsubject-> SetState (2);//Register the Observerpsubject->attach (pobserver);p Subject->attach (pObserver2);p subject-> Notify ();//Unregister the Observerpsubject->detach (pobserver);p subject->setstate (3);p subject->notify (); Delete Pobserver;delete pobserver2;delete psubject;}

VS2013 Running results:

Example 2 code implementation:  

The target Subject here provides a registration (Attach) and logoff (Detach) operation that relies on its observer, Observer, and provides an operation to synchronize all observers that depend on it (Notify). The Observer Observer provides an update operation, noting that the update operation of Observer here does not update itself when the Observer changes the Subject target State, which is deferred until the Subject object is emitted Notify notifies all observer to modify (call Update).

#include <iostream> #include <string> #include <list>using namespace Std;class subject;//Abstract Observer class Observer{protected:string name; Subject *sub;public:observer (string name, Subject *sub) {this->name = Name;this->sub = Sub;} virtual void update () = 0;};/ /specific observer, look at the stock's class Stockobserver:p ublic observer{public:stockobserver (string name, Subject *sub): Observer (name, sub) { }void update ();};/ /specific observer, see NBA class Nbaobserver:p ublic observer{public:nbaobserver (string name, Subject *sub): Observer (name, sub) {} void Update ();};/ /abstract Notifier class subject{protected:list<observer*> observers;public:string action;virtual void Attach (Observer*) = 0 virtual void detach (observer*) = 0;virtual void notify () = 0;};/ /Specific Notifier, Secretary Class Secretary:p ublic subject{void Attach (Observer *observer) {observers.push_back (Observer);} void Detach (Observer *observer) {list<observer *>::iterator iter = Observers.begin (); while (iter! = Observers.end ( ) {if ((*iter) = = observer) {observers.erase (ITER);} ++iter;}} void Notify () {list<observer *>::iterator iter = Observers.begin (); while (iter! = Observers.end ()) {(*iter) Update (); ++iter;}}; void Stockobserver::update () {cout << name << "received message:" << sub->action << endl;if (sub->actio n = = "BEAM director has come!") {cout << "I'll close the stock immediately, pretending to be a very serious job!" "<< Endl;}} void Nbaobserver::update () {cout << name << "received message:" << sub->action << endl;if (sub->action = = "BEAM director has come!") {cout << "I'll close the NBA right away, pretending to be a serious job!" "<< Endl;}} int main () {Subject *dwq = new Secretary ();//Create Observer
Observed objects Observer *xs = new Nbaobserver ("Xiaoshuai", dwq); Observer *zy = new Nbaobserver ("Zouyue", dwq); Observer *lm = new    Stockobserver ("Limin", DWQ);    Join the observation Queue Dwq->attach (XS);d Wq->attach (Zy);d Wq->attach (LM); Event dwq->action = "Go eat!" ";
Notify Dwq->notify (); cout << endl;dwq->action = "beam director came!"; Dwq->notify (); return 0;}

Operation Result:

  

Reference documents:

"Big talk design mode C + +"

"C + + design mode"

C + + Design pattern-Observer pattern

  

Observer pattern for Design patterns (c + +)

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.