I understand the design pattern (c + + implementation)--observer pattern (Observer pattern)

Source: Internet
Author: User
Tags ming

Overview:

The recent ups and downs of China's stock market, of course, the ups and downs of business opportunities, Xiao Ming found the consequences of business opportunities in the market, bought Chinese securities, he wants to computer client, on the web, mobile phones,IPad can be able to view the real-time securities market, How should we design our software in such a situation? We can do this: all of Xiao Ming's client subscribed to the stock of China securities, only a change in the stock, all the client will be notified and the initiative to update themselves.

This is our observer pattern, she defines a one-to-many dependency between objects, and when the state of an object changes , all objects that depend on it are notified and actively updated by themselves.

Class Diagrams and Examples:

It can be seen that the following roles are in the implementation of this observer pattern:

Abstract Theme (Subject ) Role : The subject role holds all references to the observation object in a single gathering, each subject can have no matter what number of observers. Abstract topics provide an interface to add and remove observer objects, which are also referred to as abstract observer (Observable) roles, and are generally implemented with an abstract class or an interface.

Abstract Viewer (Observer Role : Define an interface for all the detailed observers and update yourself when you get notification of the topic. This interface is called the update interface. Abstract observer roles are generally implemented with an abstract class or an interface. In this schematic implementation, the update interface only includes a method ( the update () method), which is called the Update method.

detailed topic (ConcreteSubject role : Deposit The status of the State in detail and notify all registered observers when the internal state of the detailed subject changes. The detailed subject role is also known as the detailed viewer role (concrete Observable). The detailed topic role pass often uses a detailed subclass implementation.

Detailed viewer (concreteobserver ) Role : Stores the status of the theme from the state. The detailed observer role implements the update interfaces required by the abstract viewer role in order to reconcile the state of itself with the state of the topic. If necessary, the detailed observer role can hold a reference to a detailed subject object. The detailed observer role pass is often implemented using a detailed subclass.

From the detailed topic role to the composition relationship of the abstract observer role, the detailed subject object can have arbitrarily multiple references to the abstract observer object. The use of abstract observers rather than detailed observers means that the subject object does not need to know which concreteobserver types are referenced, but only the abstract Observer types. This allows the detailed subject object to dynamically maintain a series of references to the Observer object and invoke the Update () method that each observer has in common when needed . This approach is called " Programming for Abstraction ."

Here we provide a simplistic example:

#include <iostream> #include <vector> #include <string>using namespace Std;class secretary;// Look at the shares of the colleague class (Observer, observer) classes Stockobserver{public:stockobserver (String strName, secretary* strsub) {name = Strname;sub = Strsub;} void Update ();p rivate:string name; secretary* sub;};/ /Secretary Class (Subject object, Notifier) class secretary{public:string action;void Add (stockobserver ob) {observers.push_back (OB);} void Remove (int addindex) {if (Addindex >=0 && Addindex < Observers.size ()) Observers.erase ( Observers.begin () + Addindex);} void Notify () {Vector<stockobserver>::iterator it;for (It=observers.begin (); It!=observers.end (); ++it) {(*it). Update ();}} Private:vector<stockobserver> observers;};  void Stockobserver::update () {cout << name << ":" << sub->action << ", begin to work" << Endl;} int main () {///create notifier secretary* p = new Secretary ();//observer stockobserver* S1 = new Stockobserver ("Lazy", p); stockobserver* s2 = new Stockobserver ("SnowFire", p);//Increase notification queue P-> ADD (*S1);p->add (*S2);//Event P->action = "The Boss is coming ...";//Notification p->notify ();//Dynamic Delete p->remove (0);p Notify (); return 0;}

Applicability:

1. When an abstract model has two aspects , One of them depends on another. The two are encapsulated in separate objects so that they can be independently changed and reused.

2. When a change to an object needs to change other objects at the same time , it is not known how many objects need to be changed.

3. When an object must notify other objects, it cannot assume that other objects are who. In other words , You don't want these objects to be tightly coupled.

Advantages and Disadvantages

The effect of the observer pattern has several advantages:

1. The Observer pattern creates an abstract coupling between the observer and the Observer. What is known by the observer role is just a gathering of detailed observers, each of which conforms to the interface of an abstract observer. The observer does not know what a detailed observer is, it only knows that they all have a common interface. Because the observer and the observer are not tightly coupled, they can belong to different levels of abstraction.

2. The Observer pattern supports broadcast communication. The observer will give notice to all the registered observers.

The observer pattern has some of the following drawbacks:

1. if an observer object has very many direct and indirect observers, all observers are informed that it will take a lot of time.

2. If there is a cyclic dependency between the observers, the observed will trigger a cyclic call between them, causing the system to crash. Pay special attention to this when using the observation mode.

3. Assuming that the observer's notification is asynchronous delivery via another thread, the system must ensure that the delivery is carried out in a self-consistent manner.

4. Although the Observer pattern allows the observer to know that the observed object has changed at any time, the observer pattern does not have a mechanism for the observer to know how the observed object has changed.


Other:1. The delegate and event mechanism can be used in. NET to implement the Observer pattern. the 2.JAVA provides observer and observable to help us simplify the implementation of the Observer pattern.


Lcl_data original in Csdn.net "http://blog.csdn.net/lcl_data/article/details/9208561"

Other Design Patterns please refer to: I understand the design pattern

I understand the design pattern (c + + implementation)--observer 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.