Object-oriented language design pattern--observer pattern

Source: Internet
Author: User

What is an observer?

The Observer pattern is the name of many classes that observe the primary class, and if the primary class triggers the event, all the observer classes are notified.

If you don't understand the observer pattern, I'll use some simple explanations to make you understand.

In this way, all the newspaper is the Observer, the newspaper is the thread, the newspaper (thread) triggered the event will be told to sell the newspaper (subject), told him to send the newspaper (send the incident). And then we have the observer .

What's the use of this?

Maybe someone will ask what's the use of this thing before they learn new knowledge, in fact, I personally think that the observer design pattern is generally used to monitor mouse events, keyboard events, or other custom events.

Because we basically write a function and wait for the event to be good.

So. How should the code be implemented? Because Java has been implemented in head first, I wrote it in the C + + language.

Frame Diagram

First, the approximate frame chart:

In general

Where the shell is selling newspapers. all the sellers are going to implement the Subject interface (generally one, of course, you can also many to many)

SHELLP pash IDs are all newspaper-ordered. all the papers have to be made. Observe Interface

The code is as follows:

Note To add:

1 #include <iostream>2 #include <vector>  vector How to use, if you are familiar with Java, you can think of it as ArrayList class 3 4 using namespace std;

Specific Code implementation

First, we first implement the base class

1 /*Observer abstract base class*/2 classObserver3 {4  Public:5     //The arguments here are string to tell you that you can pass classes, or even pass other6     Virtual voidUpdata (Const Char* str) =0;7     //Note that you should write a virtual destructor when you use it in your real project .8 9};
1 /*Topic abstract base class*/2 classSubject3 {4  Public:5 6     Virtual voidEventobserver () =0;//Event Triggering! Other programs to use7     Virtual voidRegisterobserver (Observer *) =0;//Register as an observer8     Virtual voidRemoveobserver (Observer *) =0;//Managers delete themselves9 Ten};

Well, that's basically it. So let's implement the theme: Inherit subject.

1 /*Shell Inheritance Topic*/2 classShell: PublicSubject3 {4 Private:5Std::vector <Observer*>list;6 7  Public:8     //Implementation Method9InlineVirtual voidEventobserver ()Ten     { OneVector<observer*>:: iterator it; A         intz=0; -          for(it = List.begin (); it < List.end (); it++,z++)//Transmitter Traversal -         { the  -(*it)->updata ("hello!"); ///To a function that triggers the observe base class to each observer (listener), which is equivalent to sending an event  -         } -     }; +InlineVirtual voidRegisterobserver (Observer *ob) // Register as an observer   -     { + list.push_back (OB);//add A     }; atInlineVirtual voidRemoveobserver (Observer *ob) -     { -Vector<observer*>:: iterator it; -         intz=0; -          for(it = List.begin (); it < List.end (); it++,z++)//Transmitter Traversal -         { in             if(&ob = = &*it) { -                 //If the same address is deleted toList.erase (List.begin () +z); +             } -         } the     }; *};

Then we like the concept map, we save time, only two observers (equivalent to the listener of the event)

1 /*Dis Viewer*/2 classDis: PublicObserver3 {4  Public:5InlineVirtual voidUpdata (Const Char*str) //This is the method of the observe base class, where it is implemented, and the theme (shell Class) calls this method. Triggering events 6     {7cout <<"[Dis] Dataget:"<< Str <<Endl;8     };9 };Ten  One  A /*Pash Observer*/ - classPash: PublicObserver - { the  Public: -InlineVirtual~Pash () -     { -  +     }; - inline Pash () +     { A  at     }; -InlineVirtual voidUpdata (Const Char*str) //This is the method of the observe base class, where it is implemented, and the theme (shell Class) calls this method. Triggering events  -     { -cout <<"[Pash] Dataget:"<< Str <<Endl; -     }; -};

The above two classes were written, and two classes implemented the Updata function. And there are different outputs (functions).

Let's run a try?

1 /*Main function*/2 intMain ()3 {4Pash *pash =NewPash ();5Dis *dis =NewDis ();6Dis *dis2 =NewDis ();7Dis *dis3 =NewDis ();8 shell Shell;9     //InitializeTen  OneShell.registerobserver (pash);//Register A shell.registerobserver (dis); - Shell.registerobserver (DIS2); - Shell.registerobserver (DIS3); the  -Shell.removeobserver (DIS3);//Delete Dis3 -  -     //Triggering Events + Shell.eventobserver (); //This line does not have to be written here and can be triggered wherever it is needed (other threads)  -  +     //This line ignores ~ i wrote it with sublime, so add this thing to see the output AStd::cin.Get(); at     return 0; -}

Output:

So what have we done so far?

As you can see, this line:

The subclass Dis (Observer) of Observe is registered in the Shell Class (subject). And can wait for events at any time, all the same.

1 shell.registerobserver (DIS);


Activates the event from somewhere else, and then the Shell class (subject) tells all of the Observe (observers) that have been registered, triggering the " virtual void Updata (const char* str)" function ;

1  Shell.eventobserver (); // This line does not have to be written here and can be triggered at any point where it needs to be triggered (other threads)

How does that trigger?

You can go to the shell class of 16 lines "(*it)->updata ("hello!" ); "triggers for each Observe subclass that is already registered.

At this point, this is the observer design pattern.

At last

But one thing to be aware of is not that with this observer pattern, it has to be added in, and the program will be better.

design mode to be in harmony with your program, can not write a "HelloWorld" program is used in the design mode.

In a nutshell, design patterns are not rules, but patterns that you can change at any time. This is also a point that many design pattern books emphasize.

<Thanks> whether it helps you or not, thank you for your patience. If there is any mistake, also hope to advise. </Thanks>

Object-oriented language design pattern--observer pattern

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.