[Headfirst Design Mode Study Notes] 2 observer Mode

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

1. we need to understand the relationship between newspapers, subscription systems, and subscribers. The Subscriber subscribes to the system to subscribe to newspapers. Once a newspaper has a new newspaper, the subscription system will send or mail a new newspaper to the subscriber. Then, the publisher + subscriber is the observer mode, but the names are different. The topic (or observabler) is the subject of the event, and the subscriber is called The Observer (observer ), is the subject of the response. This mode defines one-to-multiple dependencies between objects. In this way, when an object changes its state, all its dependent persons will receive notifications and automatically update them, this mode loose coupling between the subject and the observer. It embodies the fourth principle:Efforts are made to design loose coupling between interaction objects.

 

2. A meteorological station-meteorological collection device-a system for publishing multiple types of meteorological versions should be established:

First, we define two interfaces. The classes that implement these two interfaces are the correspondingTheme-meteorological Collection DeviceAndObserver class-corresponding to meteorological release version:

Public interface subject {
Public void registerobserver (ObserverO );
Public void removeobserver (Observer O );
Public void policyobservers ();
}

In the topic interface, we require three methods: Registration, logout, and notification observer. We can see that we are all programming for interfaces.

 

Public interface observer {
Public void Update (float temp, float humidity, float pressure );
}

In the observer, we require a method to update the data of the released meteorological version.

 

In addition, we also need an auxiliary interface to display updated data. This is the concept of decoupling operations:

Public interface displayelement {
Public void display ();
}

 

FirstImplement a meteorological collection device based on the topic Interface:

Public class weatherdata implementsSubject{
Private arraylist observers; // maintains an observer list.
Private float temperature;
Private float humidity;
Private float pressure;
Public weatherdata (){
Observers = new arraylist (); // The list maintained to remember the observer. It is similar to the subscriber list of the publishing department.
}
Public void registerobserver (Observer O ){
Observers. Add (O );
}
Public void removeobserver (Observer O ){
Int I = observers. indexof (O );
If (I> = 0 ){
Observers. Remove (I );
}
}
Public voidNotifyobservers(){//This method notifies all registered observers
For (INT I = 0; I <observers. Size (); I ++ ){
Observer observer = (observer) observers. Get (I );
Observer. Update (temperature, humidity, pressure); // push data
}
}
Public void measurementschanged () {// This method encapsulates policyobservers.
Yyobservers ();
}
Public void setmeasurements (float temperature, float humidity, Float Pressure ){
This. temperature = temperature;
This. Humidity = humidity;
This. Pressure = pressure;
Measurementschanged (); // This method will then notify all observers
}
// Other weatherdata methods here
Public float gettemperature (){
Return temperature;
}
Public float gethumidity (){
Return humidity;
}
Public float getpressure (){
Return pressure;
}
}

 

 

Based onObserver interface for multiple meteorological releasesHere is only one example. The rest are similar:

Public class currentconditionsdisplay implements observer, displayelement {
Private float temperature;
Private float humidity;
Private subject weatherdata; // maintain a topic reference, used by the observer
Public currentconditionsdisplay (subject weatherdata ){
This. weatherdata = weatherdata;
Weatherdata. registerobserver (this); // register it when you create it. You can skip this operation.Registerobserver public method of weatherdata
}
Public void Update (float temperature, float humidity, Float Pressure) {// push interface set aside by the observer
This. temperature = temperature;
This. Humidity = humidity;
Display ();
}
Public void display (){
System. Out. println ("current conditions:" + Temperature
+ "F degrees and" + humidity + "% humidity ");
}
}

 

Let's test this program:

Public class weatherstation {

Public static void main (string [] ARGs ){
Weatherdata = new weatherdata ();
Currentconditionsdisplay currentdisplay =
New currentconditionsdisplay (weatherdata );
Statisticsdisplay = new statisticsdisplay (weatherdata );
Forecastdisplay = new forecastdisplay (weatherdata );

Weatherdata. setmeasurements (80, 65, 30.4f );
Weatherdata. setmeasurements (82, 70, 29.2f );
Weatherdata. setmeasurements (78, 90, 29.2f );
}
}

Note that the host mainly uses the "push" method for data transmission. Summary:

 

The subject is the unit of event occurrence, and the observer is the unit of response to the event. Naturally, there may be multiple observers interested in the occurrence of an event, so there is a list of maintenance observers within a topic. At the same time, the observer must specify the events that are interested in (registerobserver). Therefore, the observer must have an internal topic instance. Of course, if the observer is no longer interested in this event, you can also use the instance of this topic to complete (unregisterobserver ).

 

When an event occurs, the topic notifies the observer on the list and can push data through parameter data transmission. (another method is that the topic provides an interface for the observer to call, that is, the so-called "pull" method). When the observer receives the Event Notification (update), the corresponding action is taken.

 

Finally, an example is provided to illustrate the application of this mode. In interface programming, a button often registers an onclicklistener, which contains the onclickaction method to respond to the clicks. At this time, the button acts as the topic, onclicklistener is the observer, while onclickaction corresponds to the update method in which the observer responds to the event.

 

UML diagram:

 

 

 

 

3. Java built-in observer Mode

We use the built-in observer mode in Java to implement the project of the weather station again (omitted the process of importing the appropriate package ):

Public class weatherdataExtends observable {// Directly inherits the topic superclass provided by Java. Note that observable is a class.
Private float temperature;
Private float humidity;
Private float pressure;
Public weatherdata (){}// Because the built-in topic is used, you do not need to manually maintain an observer list.
Public void measurementschanged (){
Setchanged ();// Indicates that the data has been updated. It is a built-in method.
Yyobservers ();// If a call with parameters is not used, it means that the data is actively pulled when the observer needs it.
}
Public void setmeasurements (float temperature, float humidity, Float Pressure ){
This. temperature = temperature;
This. Humidity = humidity;
This. Pressure = pressure;
Measurementschanged ();
}
Public float gettemperature (){// The following three methods are provided in combination with the "pull" data mode.
Return temperature;
}
Public float gethumidity (){
Return humidity;
}
Public float getpressure (){
Return pressure;
}
}

Now we create another meteorological version that uses the Java built-in observer mode:

Public class currentconditionsdisplayImplements observer, Displayelement {// Note that observer is an interface
Observable observable; // reference of the topic, used for registration, logout, and other operations
Private float temperature;
Private float humidity;
Public currentconditionsdisplay (observable ){
This. observable = observable;
Observable. addobserver (this );// You have registered and can also use
}
Public void Update (Observable OBS, object ARG){
If (OBS instanceof weatherdata ){// Determine if it belongs to the weatherdata class
Weatherdata = (weatherdata) obs;
This. temperature = weatherdata. gettemperature ();// The pull method is shown here.
This. Humidity = weatherdata. gethumidity ();
Display ();
}
}
Public void display (){
System. Out. println ("current conditions:" + Temperature
+ "F degrees and" + humidity + "% humidity ");
}
}

Let's write the test code again:

Public class weatherstation {

Public static void main (string [] ARGs ){
Weatherdata = new weatherdata ();
Currentconditionsdisplay currentconditions = new currentconditionsdisplay (weatherdata );
Statisticsdisplay = new statisticsdisplay (weatherdata );
Forecastdisplay = new forecastdisplay (weatherdata );

Weatherdata. setmeasurements (80, 65, 30.4f );
Weatherdata. setmeasurements (82, 70, 29.2f );
Weatherdata. setmeasurements (78, 90, 29.2f );
}
}

The built-in observer mode has obvious defects. First, it is a class, which is not in line with our first principle, if a class wants to complete the functions inherited from the other in the Observer mode, it will be in a dilemma. In addition, it sets the key method setchanged () to protected, which means that you must inherit the observable; otherwise, you cannot create an observable instance and combine it into your designed object.

 

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

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.