The observer pattern for Java design Patterns and the role in Java

Source: Internet
Author: User

 The Observer pattern is the behavior pattern of the object, also called the Publish-subscribe (publish/subscribe) mode, the Model-view (Model/view) mode, the source-listener (Source/listener) mode, or the slave (dependents) mode.

The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. When the subject object changes in state, all observer objects are notified so that they can automatically update themselves.

Push models and pull models

In the observer mode, it is divided into two ways: push model and pull model.

Push Model

  The subject object pushes the details of the topic to the observer, and the information that is pushed is usually all or part of the data of the subject object, regardless of whether or not the observer needs them.

Pull Model

The Subject object transmits only a small amount of information when it notifies the observer. If the observer needs more specific information, the Observer takes the initiative to get to the subject object, which is equivalent to the observer pulling data from the subject object. In the general implementation of this model, the subject object itself is passed to the observer through the update () method, which can be obtained by this reference when the observer needs to obtain the data.

According to the above description, it is found that the previous example is a typical push model, the following gives an example of a pull model.

Java-provided support for observer patterns

In the Java language Java.util Library, a observable class and a observer interface are provided, which form the Java language support for the Observer pattern.

Observer interface

This interface defines only one method, the update () method, which is called by the Notifyobservers () method of the Observer object when the state of the object being observed changes.

Public interface Observer {    void update (Observable o, Object arg);}
Observable class

The Observer class is a subclass of the Java.util.Observable class. Java.util.Observable provides a public way to support the Observer object, where two of these methods are important for observable subclasses: one is setchanged () and the other is Notifyobservers (). The first method setchanged () is called and an internal tag variable is set, representing the state of the object being observed to change. The second is notifyobservers (), which, when called, invokes the update () method of all registered observer objects so that the observer objects can update themselves.

public class Observable {Private Boolean changed = FALSE;       Private Vector Obs; /** Construct an Observable with zero observers.    */Public Observable () {obs = new Vector ();            /** * Add an observer to the Observer aggregation */public synchronized void Addobserver (Observer o) {if (o = = null)    throw new NullPointerException ();    if (!obs.contains (o)) {obs.addelement (o); }}/** * Remove an observer from the Observer aggregation */public synchronized void Deleteobserver (Observer o) {obs.removeeleme    NT (o);    } public void Notifyobservers () {notifyobservers (null); }/** * If this object changes (at that time the Haschanged method returns True) * Call this method to notify all registered observers that the update () method that called them is passed in this and arg as parameters */Publ    IC void Notifyobservers (Object arg) {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);    }/** * Will gather the observers to empty */public synchronized void Deleteobservers () {obs.removeallelements ();    }/** * Set "changed" to True */protected synchronized void setchanged () {changed = TRUE;    }/** * Resets "changed" to False */protected synchronized void clearchanged () {changed = FALSE;    }/** * Detects if this object has changed */public synchronized Boolean hasChanged () {return changed;     }/** * Returns the number of observers of this <tt>Observable</tt> object.     * * @return The number of observers of this object.    */Public synchronized int countobservers () {return obs.size (); }}

This class represents an observer object, sometimes called a subject object. An observer object can have several observer objects, and each observer object is an object that implements the Observer interface. When the observer changes, the observable's Notifyobservers () method is called, which invokes the update () method of all the specific observers, so that all observers are notified to update themselves.

This article links http://www.cnblogs.com/java-my-life/archive/2012/05/16/2502279.html

The observer pattern for Java design Patterns and the role in Java

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.