Java observer Mode

Source: Internet
Author: User

Concept

The observer mode defines the one-to-many dependency between objects. When the State of an object (the observed object) changes, all objects dependent on it (the observer) are notified and automatically updated. The implementation of the observer design pattern provided by JDK is composed of Java. util. observable class and Java. util. Observer interface. From the name, we can clearly see the roles played by the two in the Observer Design Mode: the observer is the observer role, and the observable is the subject role.

Related Classes

1.ObervableClass

This class represents the observable object in the Model View Example, and its class inherits to represent the applicationProgramThe object to be observed. An observable object can have one or more observers. The observer is any object that implements the observer interface. After an observable instance changes, the application that calls the observable notifyobservers method will call the observer's update method to notify the observer that the instance has changed.

Method Summary

Void

Addobserver(Observer O)
If the observer is different from the existing observer in the Set, add the observer to the object's observer set. The order in which notifications are sent to multiple observers is not specified.

Protected void

Clearchanged()
Indicates that the object is no longer changed, or it has notified all its observers of the latest change, so the haschanged method returns false. The yyobservers method automatically calls this method.

Int

Countobservers()
Returns the number of observers of the observable object.

Void

Deleteobserver(Observer O)
Deletes an observer from the object's observer set. Null passed to this method is invalid.

Void

Deleteobservers()
Clear the observer list so that this object no longer has any observer.

Boolean

Haschanged()
Whether the test object is changed. True is returned only when the setchanged method is recently called on this object; otherwise, false is returned.

Void

Notifyobservers()
If the haschanged method indicates that the object has changed, it notifies all its observers and calls the clearchanged method to indicate that the object will not change.

Each Observer has its update method. Its call parameters include the observable object and null. In other words, this method is equivalent to: policyobservers (null)

Void

Notifyobservers(Object Arg)
If the haschanged method indicates that the object has changed, it notifies all its observers and calls the clearchanged method to indicate that the object will not change.

Each Observer has its update method. Its call parameters include the observable object and Arg parameter. Arg can be any object

Protected void

Setchanged()
Mark thisObservableThe object is a changed object; nowHaschangedMethod will returnTrue.

 

Order of notifications

The default implementation provided in the observable class will notify observers according to the order of their registration importance, but the subclass may change this order, so as to send notifications on individual threads in a non-fixed order, alternatively, its subclass may follow the selected sequence.

Note: This notification mechanism has nothing to do with the thread andObjectClassWaitAndNotifyThe Mechanism is completely independent.

Create a newObservableWhen an object is created, its observer set is empty. When and only whenEqualsThe method is returned by two observers.TrueThey are the same.

 

2.OberverInterface

This is an interface class, which has only one abstract method for implementation update. The object implementing this interface becomes the observer, and the object must implement the update method. After the notifiyobservers method is used for the instance entry of the object registered with this object (observer), the observer automatically executes the update method.

Method Summary

Void

Update(Observable o, object Arg)
This method is called as long as the observable object is changed.

O-observable object.

Parameters of the Arg-policyobservers method.

 

Instance

This instance simulates the water burning process, involving three objects: Heater (water heater), display (Display), and alarm (Alarm ).

Simulation process: in order to facilitate the operation, the initial temperature of the water is 90, the boiling point is 95, the display according to the temperature of the water heater, the display temperature is 95, the alarm starts. Obviously, it can be seen that heater is subject, display is its obsrver, and display is also subject, because it is to be observed by the alarm, so alarm is the observer of display.

 

Heater. JavaClass

Public ClassHeaterExtendsObservable {

Private IntTemperature;

 

Public IntGettemperature (){

ReturnTemperature;

}

 

Public VoidSettemperature (IntTemperature ){

This. Temperature = temperature;

}

 

Public VoidBoilwater (){

For(IntI = 90; I <110; I ++ ){

Temperature = I;

This. Setchanged ();

This. Yyobservers ();

}

}

}

 

Display. JavaClass

Public ClassDisplayExtendsObservableImplementsObserver {

PrivateString status = "not enabled ";

 

PublicString getstatus (){

ReturnStatus;

}

 

Public VoidSetstatus (string status ){

This. Status = status;

}

 

@ Override

Public VoidUpdate (observable o, object Arg ){

This. Displaytemperature (heater) O). gettemperature ());

}

 

Private VoidDisplaytemperature (IntTemperature ){

If(Temperature> 100 ){

This. Setstatus ("Boiling ");

This. Setchanged ();

This. Notifyobservers (temperature );

}

System.Out. Println ("status:" + status + "Current temperature:" + temperature );

}

}

 

Alarm. JavaClass

Public ClassAlarmImplementsObserver {

@ Override

Public VoidUpdate (observable arg0, object arg1 ){

This. Makealarm (integer) arg1 );

}

 

Private VoidMakealarm (IntTemperature ){

System.Out. Println ("tick... The water has been burned out ");

// System. Out. println ("current water temperature:" + temperature );

}

}

 

Testmain. JavaTest entry

Public class testmain {

Public static void main (string [] ARGs ){

Heater heater = new heater ();

Display display = New Display ();

Alarm alarm = new alarm ();

Heater. addobserver (Display );

Display. addobserver (Alarm );

Heater. boilwater ();

}

}

Advantages

    • Supports loose coupling and reduces dependencies.The client no longer depends on the observer, because the client is isolated by using the subject and observer interfaces. Many frameworks have this advantage, and application components in these frameworks can be registered as notified when (low-level) Framework events occur. As a result, the Framework calls the application component but does not depend on it.
    • The number of inspector is variable.The observer can be attached and detached at runtime, because the subject has no assumptions about the number of observer. This function is useful in the following situations: the number of inspector is unknown during design. For example, if you need an observer for each window opened in an application.

Disadvantages

    • Reduced performance.In many implementations, the update () method of the observer may be executed in the same thread as the subject. If the observer list is long, it may take a long time to execute the notify () method. The dependency of the extracted object does not mean that adding the observer has no impact on the application.
    • Memory leakage.The callback mechanism used in The Observer (when the object is registered for future calls) will produce a common error, resulting in Memory leakage, or even in the hosted C #Code. Assuming that the observer is out of scope, but the user forgets to cancel the subscription to the subject, the subject still retains the reference to the observer. This reference prevents spam from allocating the memory associated with the observer before the subject object is damaged. If the lifetime of the observer is much shorter than the lifetime of the subject (usually this case), it will cause serious memory leakage.
    • Hidden dependencies.The use of the observer converts explicit dependencies (called by method) to implicit dependencies (through the observer ). If the observer is widely used throughout the application, it is almost impossible for developers to viewSource codeTo understand what is happening. In this way, it is very difficult to understand the meaning of code changes. This problem increases dramatically with the propagation level (for example, serving as a subject observer ). Therefore, the observer should be used only in a few well-defined interactions (for example, interactions between models and views in Model-View-controller mode. It is best not to use an observer between domain objects.
    • Test / Debugging is difficult.Although loose coupling is a major architectural feature, it can make development more difficult. The more decoupling two objects, the more difficult it is to understand the dependencies between them when you view the source code or class relationship diagram, only when the association between two objects can be safely ignored should they be loosely coupled (for example, if the observer has no side effects ).

ReferenceArticle:

Http://baike.baidu.com/view/6547055.htm

http://msdn.microsoft.com/zh-cn/library/ms978753.aspx

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.