Design Pattern-Observer Pattern)

Source: Internet
Author: User

Design Pattern ------ Observer Pattern)


Definition: Observer mode-define one-to-multiple dependencies between objects. In this way, when an object changes its status, all objects dependent on it will be notified and updated automatically.

In the idea of OO design, we emphasize that our design is always working towards loose coupling of interaction between objects. The observer mode is used to find a loosely coupled Implementation Method in one-to-many dependencies. In our daily life, we often encounter this situation, that is, an object has certain States, and other objects need to use these States to execute certain behaviors. For example, in a data control center, there is a device responsible for collecting data and notifying other parts of the data in real time. These departments need to use the data. Therefore, this is a one-to-many dependency. Suppose we describe this model with a satellite control system.

Assume that the system acts as a data collection center to obtain real-time satellite data, such as longitude, latitude, and flight time.

China and the West are responsible for notifying other Departments of the collected data in a timely manner. Assume that there are two departments, one is responsible for displaying the current status of the satellite in real time, and the other is responsible, calculates the received data and outputs the control signals for the next step. In addition, the system is not complete enough, and new departments may be added. This department also needs to use real-time satellite data for other work.

Based on the above system requirements, we can know that this is a one-to-many relationship and requires good system scalability, that is, the coupling between system objects is small. So how can we implement it?

The system has a data collection center. We need to design a class to describe this data collection center. Assume It is called satellitedata,

The display department is also described in the displayboard class and the calculation Department class calculate. The satellitedata class is defined as follows:

Class satellitedata

{

Float longpolling;

Float latitude;

Float timelast;

Public float getlongpolling ()

{

......

}

Public float getlatitude ()

{

......

}

Public float gettimelast ()

{

......

}

Public setchange ()

{

Longpolling = getlongpolling ();

Latitude = getlatitude ();

Timelast = gettimelast ();

Displayboard. Update (longitudu, latitude, timelast );

Calculate. Update (longitudu, latitude, timelast );

}

}

Displayboard is the displayboard-like object, and calculate is the calculate object. Let's take a look at this piece of code, which actually violates the idea of interface-oriented programming that we emphasize in the Policy mode. The red part of the code is implementation-oriented, send notifications for objects that require these statuses. In this way, if you add a new object, you need to modify the code of the satellitedate class. In addition, this causes great coupling.

So how can we solve this problem using the observer mode? The observer mode defines one-to-many dependencies. "One" is called the topic, and "multiple" is called the observer. The observer subscribes to a topic by registering the topic. When the topic is not required, the observer cancels the subscription. In this way, multiple observers share the content in the topic through subscription. When the theme content changes, it is necessary to notify the observer dynamically so that they can respond even if they make a response.

In observer mode, the topic implements the subject interface. The subject interface mainly defines three methods: registering an observer, notifying the observer of the current status, and deleting an observer.

Definition:

Interface subject

{

Public void registeroberserver (oberserver O );

Public void incluyoberservers (oberserver O );

Public void deleteoberserver (oberserver O );

}

In the parameters of each method, oberserver is the observer interface, and the specific observer implements this interface. Here, we embody the idea of interface-oriented programming.

The observer object needs to implement the oberserber interface, which mainly defines the update method, update (). This method is mainly used to call the topic in updating the status, so that in interface-oriented programming, the topic only cares about the method implemented by the interface. The topic does not care about which class is implemented. Let's look at the related class diagram.

The class diagram shows that the satellitedata class implements the subject interface, while the displayboard class and the calculate class also implement the oberserver interface, and satellitedata has multiple registered observers, the observer shares the same topic. The Code is as follows:

// Topic Interface Definition

Interface subject

{

Public void registeroberserver (oberserver O );

Public void incluyoberservers (oberserver O );

Public void deleteoberserver (oberserver O );

}

// Observer Interface Definition

Interface oberserver

{

Public void Update (float longtitude, float latitude, float lasttime );

}

// Satellite Data Definition

Class satellitedata

{

Float longpolling;

Float latitude;

Float timelast;

Arraylist oberservers; // list of registered observers

Public satellitedate ()

{

Oberservers = new arralylist ();

}

Public float getlongpolling ()

{

......

}

Public float getlatitude ()

{

......

}

Public float gettimelast ()

{

......

}

Public setchange ()

{

Longpolling = getlongpolling ();

Latitude = getlatitude ();

Timelast = gettimelast ();

Notifyoberservers ();

}

Public void registeroberserver (oberserver O)

{

Oberservers. Add (O );

}

Public void deleteoberserver (oberserver O)

{

Int I = oberservers. indexof (O );

Oberservers. Remove (I );

}

Public void initialize yoberservers ()

{

Longtitude = getlongtitude ();

Latitude = getlatitude ();

Timelast = gettimelast ();

For (INT I = 0; I <oberservers. Size (); I ++)

{

Oberserver = (oberserver) oberservers. Get (I );

Oberserber. Update (longpolling, latitude, timelast );

}

}

}

// Display the Department class

Class displayboard implements oberserver

{

Satellitedate data;

Public displaydata (satellitedate data)

{

This. Data = data;

}

Public void Update (float longtitude, float latitude, float timelast)

{

Syste. Out. println ("longitude" + longtitude + "latitude:" + latitude + "duration" + timelast );

 

}

// Computing class

Class calculate implements oberserver

{

 

Satellitedate data;

Public displaydata (satellitedate data)

{

This. Data = data;

}

 

Public void Update (float longtitude, float latitude, float timelast)

{

// This is the computing process

}

}

 

Observer mode summary:

1. Dependency is essential in the process of object-oriented design. We often work hard for loosely coupled design between objects. This is another criterion for our OO design, in addition to interface-oriented programming, it is also necessary to change one to one (is a to has ).

2. The applicability of the observer mode, as defined above, applies to one-to-many dependencies. Changes in the state of an object affect all other objects, for example, in the banking system, the calculation of the customer account interest is dependent on the bank's interest rate. The change of the bank's interest rate must be notified by the bank like all customers, so that the calculation result of the interest will also change. Here, a bank is equivalent to a topic, and a bank customer is the observer to subscribe to this topic. The observer mode can be applied here.

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.