Java observer Mode

Source: Internet
Author: User

Simply put, the observer mode defines a one-to-many dependency, so that one or more observer objects can monitor one topic object. Such changes in the status of a topic object can notify all observer objects dependent on this object so that these observer objects can be updated automatically.

  Structure of observer Mode

The Observer (Observer) mode is the behavior mode of an object. It is also called the Publish/Subscribe mode and the Model-View (Model/View) mode) source/Listener mode or Dependents mode.

The class diagram structure in this mode is as follows:


Figure 1. The static structure of the observer mode can be clearly viewed from the class diagram.

In observer mode, there are the following roles:

.Abstract topic role: The topic role stores reference of all observer objects in a list. Each topic can have any number of observers. A topic provides an interface to add or remove an observer object. A Topic role is also called an abstract Observable role;


Figure 2. Abstract topic role, sometimes called an abstract observer role, can be implemented using an abstract class or an interface. under specific circumstances, it is not excluded to use a specific class implementation.

.Abstract Observer (Observer) Role: Define an interface for all specific observers and update themselves when notified;


Figure 3. The abstract observer role can be implemented using an abstract class or an interface. under specific circumstances, it is not excluded to use a specific class implementation.

.ConcreteSubject role: Stores the internal states that are useful to a specific observer object. When this internal state changes, a notification is sent to the observer. A specific topic role is also called a specific observer role;


Figure 4. A Topic role is usually implemented using a specific subclass.

.ConcreteObserver role: Save a reference pointing to a specific topic object, and a status that matches the topic status. The specific observer role implements the update interface required by the abstract observer role, so that the status of the observer role is the same as that of the topic.


Figure 5. A specific observer role is usually implemented using a specific subclass.

The following shows a Java code for implementation. First, in this schematic implementation, an abstract topic role is implemented using a Java interface, which is the following Subject interface:


Public interface Subject
{
Public void attach (Observer observer );

Public void detach (Observer observer );

Void policyobservers ();
}

Code List 1: source code of the Subject interface.

This abstract topic interface specifies the operations that must be implemented by three sub-classes, that is, attach () is used to add an observer object; detach () is used to delete an observer object; and policyobservers () it is used to notify various observers to refresh themselves. Abstract topic roles actually require subclass to maintain a list of all observer objects as elements.

A specific topic is a specific class that implements the abstract topic Subject interface. It provides the specific implementation of the above three operations. From the source code below, we can see that the Java implementation provided here uses a Java vector to save all the observer objects, while attach () and detach () the operation is to increase or decrease the elements of this vector.


Import java. util. Vector;
Import java. util. Enumeration;

Public class ConcreteSubject implements Subject
{
Public void attach (Observer observer)
{
ObserversVector. addElement (observer );
}

Public void detach (Observer observer)
{
ObserversVector. removeElement (observer );
}

Public void policyobservers ()
{
Enumeration enumeration = observers ();
While (enumeration. hasMoreElements ())
{
(Observer) enumeration. nextElement (). update ();
}
}

Public Enumeration observers ()
{
Return (Vector) observersVector. clone (). elements ();
}
Private Vector observersVector = new java. util. Vector ();
}

Code List 2: source code of the ConcreteSubject class.

The implementation of the abstract observer role is actually the simplest. It is a Java interface that declares only one method, namely update (). This method refreshes itself as soon as it is called.

Public interface Observer
{
Void update ();
}

Code List 3: source code of the Observer interface.

The implementation of the observer role only involves the implementation of the update () method. The implementation of this method is closely related to the application. Therefore, this class only provides a framework.

Public class ConcreteObserver implements Observer
{
Public void update ()
{
// Write your code here
}
}

Code list 4: source code of the ConcreteObserver class.

Although the implementation method of the observer mode can be determined by the designer, the observer mode plays an important role in Java because the event model of the Windows system adopts the observer mode from AWT1.1. For this reason, the Java language provides its own support for the observer mode. Therefore, we recommend that you use the support provided by the Java language to apply the observer mode in your system.
  Support for observer mode provided by Java

In the Java. util library of the java language, an Observable class and an Observer interface are provided to support the Observer mode of the Java language.

  Observer Interface

This interface only defines one method, update (). This method is called when the state of the object to be observed changes. The implementation of this method should call the yyobservers () method of each object to notify all the observed objects.


Figure 6. Class diagram of the Observer interface provided by java. util.

 


Package java. util;

Public interface Observer
{
/**
* When the observed object changes, this method is called.
*/
Void update (Observable o, Object arg );
}

Code List 5: source code of the java. util. Observer interface.

  Observable class

The classes to be observed are subclasses of the java. util. Observable class. Java. util. Observable provides public methods to support observer objects. Two of these methods are very important to the Observable subclass: setChanged () and notifyObservers (). After the first method setChanged () is called, an internal variable is set to indicate that the State of the object to be observed has changed. The second is yyobservers (). When this method is called, the update () method of all registered observer objects is called so that these observer objects can update themselves.

The java. util. Observable class has other important methods. For example, an observer object can call the addObserver () method of the java. util. Observable class to add objects to a list one by one. When there is a change, this list tells the observer objects of the yyobservers () method that need to be notified. Because the list is private, the sub-objects of java. util. Observable do not know that the observer objects are always watching them.


Figure 7. Observer class diagram provided by Java.


Source code of Observable:


Package java. util;
Public class Observable
{
Private boolean changed = false;
Private Vector obs;

/***** // Use 0 observers to construct an observer. **/

Public Observable ()
{
Obs = new Vector ();
}

/***//**
* Add an observer to the observer list.
*/
Public synchronized void addObserver (Observer o)
{
If (! Obs. contains (o ))
{
Obs. addElement (o );
}
}

/***//**
* Deletes an observer object from the observer list.
*/
Public synchronized void deleteObserver (Observer o)
{
Obs. removeElement (o );
}

/***//**
* Equivalent to policyobservers (null)
*/
Public void policyobservers ()
{
Yyobservers (null );
}

/***//**
* If the object changes (then the hasChanged method returns true)
* This method is called to notify all registered observers that their update () method is called,
* Input this and arg as parameters.
*/
Public void policyobservers (Object arg)
{
/***//**
* Temporarily stores the status of the current observer. See memorandum mode.
*/
Object [] arrLocal;

Synchronized (this)
{
If (! Changed) return;
ArrLocal = obs. toArray ();
ClearChanged ();
}

For (int I = arrLocal. length-1; I> = 0; I --)
(Observer) arrLocal [I]). update (this, arg );
}

/***//**
* Clear the observer list
*/
Public synchronized void deleteObservers ()
{
Obs. removeAllElements ();
}

/***//**
* Set "changed" to true
*/
Protected synchronized void setChanged ()
{
Changed = true;
}

/***//**
* RESET "changed" to false
*/
Protected synchronized void clearChanged ()
{
Changed = false;
}

/***//**
* Check whether the object has changed
*/
Public synchronized boolean hasChanged ()
{
Return changed;
}

/***//**
* Return the total number of observers of the observed object (that is, this object.
*/
Public synchronized int countObservers ()
{
Return obs. size ();
}
}

Code List 6: source code of the java. util. Observer interface.

This Observable class represents an object to be observed. An Observer object can have several Observer objects. An Observer can be an object that implements the Observer interface. When the object to be observed changes, it will call the notifyObservers method of Observable. This method calls the update () method of all specific observers, so that all observers are notified to update themselves. See the following class diagram:


Figure 8. Support for observer mode provided by Java.


The order of notifications is not specified here. The default implementation provided by The Observerable class will notify the Observers objects in the registration order, but the subclass of the Observerable class can change this order. Sub-classes can also notify the observer object in a separate thread, or execute in order in a common thread.

When an observer object is created, its observer set is empty. Two observer objects are considered to be two equal objects when their equals () method returns true.
  How to use Java to support the observer Mode

To illustrate how to use the observer Mode Supported by Java, this section provides a very simple example. In this example, the observed object is called Watched, that is, the Monitored object, and the observer object is called Watcher. The Watched object inherits from the java. util. Obsevable class, while the Watcher object implements the java. util. Observer interface. Another object is Tester, which plays the role of the client.

Shows the structure of this simple system.


Figure 9. An example of using the Observer interface and the Observable class.


When the client changes the internal status of the Watched object, Watched notifies Watcher to take necessary actions.

 

Package com. javapatterns. observer. watching;

Import java. util. Observer;

Public class Tester
{
Static private Watched watched;
Static private Observer watcher;

Public static void main (String [] args)
{
Watched = new Watched ();

Watcher = new Watcher (watched );

Watched. changeData ("In C, we create bugs .");
Watched. changeData ("In Java, we inherit bugs .");
Watched. changeData ("In Java, we inherit bugs .");
Watched. changeData ("In Visual Basic, we visualize bugs .");
}
}


Code List 7: source code of the Tester class.

 

Package com. javapatterns. observer. watching;

Import java. util. Observable;

Public class Watched extends Observable
{
Private String data = "";

Public String retrieveData ()
{
Return data;
}

Public void changeData (String data)
{
If (! This. data. equals (data ))
{
This. data = data;
SetChanged ();
}

Yyobservers ();
}
}


Code List 8: source code of the Watched class.

 

Package com. javapatterns. observer. watching;

Import java. util. Observable;
Import java. util. Observer;

Public class Watcher implements Observer
{
Public Watcher (Watched w)
{
W. addObserver (this );
}

Public void update (Observable ob, Object arg)
{
System. out. println ("Data has been changed to: '" + (Watched) ob). retrieveData () + "'");
}
}


Code List 9: source code of the Watcher class.

It can be seen that although the client assigns four values to the internal status of the Watched object, the value changes only three times:

Watched. changeData ("In C, we create bugs .");
Watched. changeData ("In Java, we inherit bugs .");
Watched. changeData ("In Java, we inherit bugs .");
Watched. changeData ("In Visual Basic, we visualize bugs .");


Code List 10: the internal status of the observer has changed.

Correspondingly, the Watcher object reports three changes. The following information is printed by the runtime program:

 

Data has been changed to: 'In C, we create bugs .'

Data has been changed to: 'In Java, we inherit bugs .'

Data has been changed to: 'In Visual Basic, we visualize bugs .'


Code List 11: running result.

  Bodhisattva bottle-holding turtles

I want to go to the Putuo mountains in the South China Sea to ask the Bodhisattva to fall down to the monster baby to save the monk's Monk. "I heard that the Bodhisattva... hate, the hands of the pearl bottle into the heart of the Sea throw a hole... when I saw the sea, I jumped into the waves and drilled out a bottle. It turned out to be a monster rolling out... please be aware of this strange name and surname."

Using object-oriented language description, the tortoise is an observer object, and the topic of observation is Bodhisattva. Once the Bodhisattva reaches the sea, it symbolizes that the Bodhisattva called the notifyObservers () method as the topic. In travel to the West, there are two observer objects: A tortoise and a Wukong. Wukong's response is not considered here, and the tortoise's response is to bring the bottle back to the coast.


Figure 10. Bottle-holding Turtles of the Bodhisattva and the Bodhisattva.

 
Bodhisattva, as the object to be observed, inherits from the Observable class, while bottle-holding turtles, as the Observer, inherit from the Observer interface. The implementation of this simulation system can be achieved by using Java to support the Observer mode.

  DEM event mechanism in Java

  DEM mechanism in AWT

The responsibility chain model chapter mentioned that the AWT1.0 event processing model is based on the responsibility chain. This Model is not applicable to complex systems. Therefore, in AWT1.1 and later versions, the Event processing Model is a delegate Event Model (Delegation Event Model or DEM) based on the observer mode ).

In the DEM model, the topic role is responsible for publishing (publish) events, while the observer role subscribes to events that interest a specific topic (subscribe. When an event is generated for a specific topic, it notifies all interested subscribers.

The basic design goal of this publishing-subscription mechanism is to provide a form of loose coupling between publishers and subscribers, and a way to dynamically register and cancel subscription requests to a publisher. Obviously, the technique to implement this idea is to design abstract interfaces and separate the abstract layer from the concrete layer. This can be seen clearly in the Observer mode.

When DEM is used, the publisher is called the event source, and the subscriber is called the event listener ). In Java, events are represented by classes. The release of events is done by synchronously calling member methods.

  DEM mechanism in Servlet Technology

The DEM event model used in AWT is actually applied to all Java event mechanisms. The event processing mechanism in Servlet technology is also the DEM model used.

  DEM mechanism in SAX2 Technology

The DEM event model is also applied to the event processing mechanism of SAX2.

  Observer Effect

The observer mode has the following effects:Advantages:

First, the observer mode establishes an abstract coupling between the observer and the observer. What the observer role knows is a specific observer list. 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. If the object is thrown together by both the observer and the observer, the object must span the abstract and concrete layers.

Second, the observer mode supports broadcast communication. The observer will send a notification to all registered observers,

The observer mode has the followingDisadvantages:

First, it takes a lot of time to notify all observers if they have many direct and indirect observers.

Second, 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 observer mode.

Third, 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.

Fourth, although the observer pattern can enable the observer to know that the observed object has changed at any time, the observer pattern does not have a mechanism to let the observer know how the observed object has changed.

  Relationship between observer mode and other modes

The observer mode uses the Memento Pattern mode to temporarily store the observer object in the object to be observed.

  Q &

First, my sister and I said to my mother, "Mom, my sister and I are playing in the courtyard. When the meal is ready, let us say it ." What is the mode? Can you give a class chart description?

  Q & A answers

The first answer is the observer mode. My sister and I asked my mother to tell us that the meal was ready so that we could have dinner. In a more technical language, when the subject (meal) of the system changes, it will tell the other part of the system (the observer, namely mom, me, and Sister ), so that it can adjust the internal status (there are preparations to start eating), and take corresponding actions (EAT ).

The system class diagram is described as follows.


Figure 11. system class diagram.

 

 

Reprinted to http://www.blogjava.net/supercrsky/articles/202544.html

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.