Design Pattern Ten: The Observer Pattern (Observer)

Source: Internet
Author: User

Viewer mode:
Defines a one-to-many dependency between objects, and when an object changes its state, all objects that depend on it automatically receive notifications and update their state.

aone-tooneand updated automatically.

UML diagram:

Mainly include:

    1. Subjcet (Stock): Abstract theme character, save all observers to a collection, each theme character can have any number of observations. and provides an interface to add and remove observations.
    2. ConcreteSubject (IBM): A specific topic role. Saves information about the state and sends the message to all observers when its state changes.
    3. Observer (iinverstor): The abstract viewer role. Defines an interface that updates itself, which is called when the subject role state changes.
    4. Concreteobserver (Investor): The specific observation, holding a reference to a subject role, implements the interface of an abstract observer-defined update itself, so that its state can be reconciled with the state of the subject.

The C + + code for the Observer pattern is implemented as follows:

#include <iostream>#include <stdlib.h>#include <stdio.h>#include <string>#include <list>using namespace STD;classSubject;classobserver{ Public: Observer () {} Observer (subject* s),stringn) {subject=s;            Name=n; }Virtual voidUpdate () =0;stringGetName () {returnName } Subject * Getsubject () {returnSubject }Private: Subject *subject;stringname;};classsubject{ Public:voidAttach (Observer * o) {lists.push_back (o); }voidDetach (Observer * o) {lists.remove (o); }voidNotify () { list<observer *>:: Iterator Iter=lists.begin (); for(; Iter!=lists.end (); iter++)                {(*iter)->update (); }            }Virtual stringGetState () =0;Private: list<Observer*>Lists;};classConcreteSubject: Publicsubject{ Public:stringGetState () {stringStr"ConcreteSubject notify");returnStr }};classConcreteobserver: Publicobserver{ Public: Concreteobserver (Subject * s,stringN): Observer (s,n) {}voidUpdate () {STD::cout<<getname () <<"Update from"<<getsubject ()->getstate () <<STD:: Endl; }};intMain () {Subject *s=NewConcreteSubject (); Observer *o1=NewConcreteobserver (s),"Bill."); Observer *o2=NewConcreteobserver (s),"Joe");    S->attach (O1);    S->attach (O2); S->notify ();DeleteSDeleteO1;DeleteO2;return 0;}

Execution output:

Here is a specific example:

    1. Subject as stock (stock)
    2. ConcreteSubject is IBM (stock of IBM) and shares of other companies
    3. Observer for Iinvestor (investor interface)
    4. Concreteobserver for investor (for a specific investor, i.e. a person holding a stock)

A stock can be held by multiple investors, that is, there is a one-to-many dependency, and when the price of a stock changes, it is necessary to inform all investors holding the stock (i.e. the observer).

The UML class diagram is as follows:

The C + + code is implemented as follows:

#include <stdlib.h>#include <stdio.h>#include <iostream>#include <string>#include <list>using namespace STD;classStock;classiinvestor{ Public: Iinvestor () {} iinvestor (stringStr,stock *s): Name (str), stock (s) {} stock * Getstock () {returnStock }stringGetName () {returnName }Virtual voidUpdate () =0;Private: Stock * STOCK;//Investment in stock            stringName//Investor name};classstock{ Public: Stock () {} stock (stringStrDoublep): Symbol (STR), Price (p) {}voidSetprice (Doublep) {price=p; Notify ();STD::cout<<STD:: Endl; }DoubleGetPrice () {returnPrice }stringGetsymbol () {returnSymbol }voidAttach (Iinvestor * ii) {Investors.push_back (ii); }voidDeattach (Iinvestor *ii) {investors.remove (ii); }voidNotify () { list<IInvestor*>:: Iterator Iter=investors.begin (); for(; Iter!=investors.end (); iter++)                {(*iter)->update (); }            }Private:stringSymbol//Stock name            DoublePrice//Stock price             list<iinvestor *>Investors;//Investors};classIbm: Publicstock{ Public: IBM () {} IBM (stringSymbolDoublePrice): Stock (Symbol,price) {}};classInvestor: Publiciinvestor{ Public: Investor () {} Investor (stringN,stock *s): Iinvestor (n,s) {}voidUpdate () {STD::cout<<"notified"<<getname () <<"of"<<getstock ()->getsymbol () <<"' s change to"<<getstock ()->getprice () <<STD:: Endl; }};intMain () {STD::cout<<"The realization of the observing mode of stock trading"<<STD:: Endl; IBM *ibm=NewIBM ("IBM",120.10); iinvestor* investor1=NewInvestor ("Sorros", IBM); iinvestor* investor2=NewInvestor ("Berkshire", IBM);    Ibm->attach (Investor1);    Ibm->attach (INVESTOR2); Ibm->setprice (120.50); Ibm->setprice (120.75);DeleteIBMDeleteInvestor1;DeleteInvestor2;return 0;}

Execution Result:

Design Pattern Ten: The Observer Pattern (Observer)

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.