I understand the design pattern (C ++ implementation)-Observer Pattern)

Source: Internet
Author: User
Overview:

Recently, the stock market in China has been ups and downs. Of course, the ups and downs have used business opportunities. James found that business opportunities are broken and he wants to enter the market and buy Chinese securities. He wants to go to computer clients, webpages, and mobile phones, on the iPad, we can view the real-time quotations of this securities. In this case, how should we design our software? We can: all clients of James subscribe to the stock of China Securities. As long as the stock changes, all clients will be notified and automatically updated.

This is our observer mode. She defines a one-to-many dependency between objects. When the State of an object changes, all objects dependent on it are notified and automatically updated.

Class Diagram and instance:

We can see that in the implementation of this observer mode, there are the following roles:

Abstract topic (Subject) Role: The topic role stores all references to the observed objects in one aggregation. Each topic can have any number of observers. An abstract topic provides an interface to add and delete observer objects. A Topic role is also called an abstract observer role. It is generally implemented using an abstract class or an interface.

Abstract observer (Observer) Role: Defines an interface for all the specific observers and updates themselves when receiving notifications of the topic. This interface is called the update interface. Abstract observer roles are generally implemented using an abstract class or an interface. In this schematic implementation, the update Interface contains only one method (that is, the update () method). This method is called the update method.

Concretesubject) Role: Stores the relevant status to a specific observer object. When the internal status of a specific topic changes, a notification is sent to all registered observers. A topic role is also called a concrete observable ). A topic role is usually implemented by a specific subclass.

Concreteobserver) Role: The storage status is the same as that of the topic. The observer role implements the update interface required by the abstract observer role, so that the state of the observer can be consistent with the state of the topic. If necessary, the observer role can save a reference pointing to a specific topic object. A specific observer role is usually implemented by a specific subclass.

The synthesis relationship between a specific topic role and an abstract observer role indicates that a specific topic object can be referenced by any number of abstract observer objects. The use of abstract observer instead of specific Observer means that the topic object does not need to know which concreteobserver types are referenced, but only the abstract observer type. This allows a specific topic object to dynamically maintain a series of references to the observer object and call the update () method shared by each observer as needed. This is called "abstract programming ".

Here we provide a simple example:

# Include <iostream> # include <vector> # include <string> using namespace STD; class secretary; // class stockobserver {public: stockobserver (string strname, Secretary * strsub) {name = strname; sub = strsub;} void Update (); Private: string name; Secretary * sub ;}; // category 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 a notifier Secretary * P = new secretary (); // observer stockobserver * S1 = new stockobserver ("lazy", P); stockobserver * S2 = new stockobserver ("snowfire", P ); // Add to notification queue p-> Add (* S1); P-> Add (* S2); // event p-> action = "the boss is coming... "; // notification p-> Y (); // dynamically Delete P-> remove (0); P-> notify (); Return 0 ;}

Applicability:

1. When an abstract model has two aspects, one of which depends on the other. Encapsulate the two in independent objects so that they can be changed and reused independently.

2. When changing an object, you need to change other objects at the same time without knowing how many objects need to be changed.

3. When an object must notify other objects, it cannot assume who the other objects are. In other words, you do not want these objects to be tightly coupled.

Advantages and disadvantages:

The observer mode has the following advantages:

1. The observer mode establishes an abstract coupling between the observer and the observer. What the observer role knows is that a specific observer aggregates, and each specific observer conforms to an abstract observer interface. The observer does not know any specific observer, but only knows that they all have a common interface. Since the observer and observer are not closely coupled, they can belong to different abstract layers.

2. The observer mode supports broadcast communication. The observer sends a notification to all registered observers.

The observer mode has the following Disadvantages:

1. if an object to be observed has many direct and indirect observers, it takes a lot of time to notify all the observers.

2. If there is a circular dependency between the observer, the observer will trigger a circular call between them, resulting in system crash. Pay special attention to this when using the observation test mode.

3. If the notification to the observer is asynchronously delivered through another thread, the system must ensure that the delivery is carried out in the correct way.

4. Although the observer mode can enable the observer to know that the observed object has changed at any time, the observer mode does not have a mechanism to let the observer know how the observed object has changed.


Others: 1. In. net, the delegate and event mechanisms can be used to implement the observer mode. 2. Java provides observer and observable to help us simplify the observer mode.

Lcl_data was originally created in csdn. Net [http://blog.csdn.net/lcl_data/article/details/9208561]

For other design patterns, see: Design patterns I understand

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.