The observer pattern of Java and design patterns

Source: Internet
Author: User

Original source: http://www.cnblogs.com/java-my-life/archive/2012/05/16/2502279.html

In Dr Shanhong's "Java and Schema" book, this describes the Observer (Observer) pattern:

  The observer pattern is the behavior pattern of the object, also known as the Publish-subscribe (publish/subscribe) mode, model-view (model/view) mode, source-listener (Source/listener) mode, or dependent (dependents) mode.

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

   A software system contains a variety of objects, like a thriving forest full of creatures. In a forest, all kinds of living things depend on each other and restrain each other, forming a biological chain. A change in the state of a creature can cause other creatures to act accordingly, and each organism is in the interaction of another organism.

Similarly, a software system often requires changes in the state of an object, and some other objects make a corresponding change. There are many design schemes to do this, but in order to make the system easy to reuse, we should choose the design scheme of low coupling degree. Reducing the coupling between objects is beneficial to the reuse of the system, but at the same time designers need to enable these low coupling objects to maintain the consistency of action and ensure a high degree of collaboration. The Observer model is the most important of the various designs that meet this requirement.

The following is an example of a simple schematic implementation to discuss the structure of the observer pattern.

The actors involved in the Observer pattern are:

Abstract Theme (Subject) role: Abstract theme Roles keep all references to observer objects in a cluster (such as a ArrayList object), each subject can have any number of observers. Abstract topics provide an interface for adding and removing observer objects, and abstract theme roles are also called abstract-observer (observable) roles.

specific Theme (concretesubject) role: The state is deposited in a specific observer object, and all registered observers are notified when the internal state of the specific subject changes. The specific theme role is also called the specific Observer (concrete observable) role.

abstract Observer (Observer) Role: defines an interface for all specific observers and updates itself when a topic is notified, an interface called an update interface.

The specific observer (concreteobserver) role: The state of the store and the topic itself. The specific observer role implements the update interface required by the abstract observer role to coordinate itself with the state of the subject. The specific observer role can maintain a reference to a specific subject object, if necessary. Source Code

Abstract Theme Role Classes

Public abstract class Subject {
    /**
     * To hold the registered observer object *
     *
    private    list<observer> List = new Arraylist<observer> ();
    /**
     * Registered Observer Object
     * @param observer Observer Object * * Public
    VOID Attach (Observer observer) {
        
        List.add ( observer);
        System.out.println ("attached an observer");
    }
    /**
     * Delete Observer object
     * @param observer Observer Object * * Public
    VOID Detach (Observer observer) {
        
        LIST.REMOVE (Observer);
    }
    /**
     * Notifies all registered Observer objects */
     public
    void Nodifyobservers (String newstate) {for
        
        (Observer observer:list) {
            observer.update (newstate);}}}

Specific Theme Role Classes

public class ConcreteSubject extends subject{
    
    private String state;
    
    Public String GetState () {return state
        ;
    }

    public void Change (String newstate) {state
        = newstate;
        System.out.println ("The theme is:" + state);
        States change, notifying each observer
        This.nodifyobservers (state);
    }

Abstract Observer Role Class

Public interface Observer {
    /**
     * Update interface
     * @param    State Update Status *
    /public void update (String State);
}

Specific observer Role class

public class Concreteobserver implements Observer {
    //Observer's state
    private String observerstate;
    
    @Override public
    void Update (String state) {
        /**
         * Updates The observer's status so that it is consistent with the state of the target * *
        observerstate = State;
        System.out.println ("Status:" +observerstate);
    }

Client class

public class Client {public

    static void Main (string[] args) {
        //Create Subject Object
        concretesubject subject = new concrete Subject ();
        Create the Observer object
        Observer Observer = new Concreteobserver ();
        Registers the Observer object on the Subject Object
        Subject.attach (Observer);
        Change the status of the Subject Object
        subject.change ("New State");
    }

The results of the operation are as follows

At run time, the client first creates an instance of the specific subject class, as well as an observer object. It then invokes the attach () method of the Subject object, registering the Observer object with the subject object, that is, adding it to the subject object's aggregation.

At this point, the client invokes the change () method of the theme, changing the internal state of the subject object. The Subject object invokes the Notifyobservers () method of the superclass when the state changes, notifying all registered observer objects. push model and pull model

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

Push Model

   The Subject object pushes the viewer to the details of the subject, regardless of whether the observer needs it, and the pushed information is usually all or part of the data of the subject object.

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 through the update () method to the observer, so that when the observer needs to obtain the data, it can be obtained by the reference.

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

  abstract Observer class for pull model

   The pull model usually passes the subject object as a parameter.

Public interface Observer {
    /**
     * Update interface
     * @param subject incoming Subject object to get the status of the Subject Object/
     public
    void update (Subject Subject);
}

  the concrete observer class of the pull model

public class Concreteobserver implements Observer {
    //Observer's state
    private String observerstate;
    
    @Override public
    void Update (Subject Subject) {
        /**
         * Updates The Observer's State, keeping it consistent
        with the target's state. Observerstate = ((concretesubject) subject). GetState ();
        SYSTEM.OUT.PRINTLN ("Observer status:" +observerstate);
    }

  abstract Theme class for pull model

   The main change in the abstract subject class of the pull model is the Nodifyobservers () method. When a loop notifies an observer, that is, a circular call to the Observer's update () method, the incoming arguments are different.

Public abstract class Subject {
    /**
     * To hold the registered observer object *
     *
    private    list<observer> List = new Arraylist<observer> ();
    /**
     * Registered Observer Object
     * @param observer Observer Object * * Public
    VOID Attach (Observer observer) {
        
        List.add ( observer);
        System.out.println ("attached an observer");
    }
    /**
     * Delete Observer object
     * @param observer Observer Object * * Public
    VOID Detach (Observer observer) {
        
        LIST.REMOVE (Observer);
    }
    /**
     * Notifies all registered Observer objects */
     public
    void Nodifyobservers () {for
        
        (Observer observer:list) {
            Observer.update (this);}}

  the specific subject class of the pull model

A little bit of change compared to the push model is that when you invoke a method that notifies the observer, you don't need to pass in the argument.

public class ConcreteSubject extends subject{
    
    private String state;
    
    Public String GetState () {return state
        ;
    }

    public void Change (String newstate) {state
        = newstate;
        System.out.println ("The theme is:" + state);
        State changes, notify each observer
        This.nodifyobservers ();
    }
comparison of two modes

The push model is the assumption that the subject object knows the data The observer needs, and the pull model is the subject object, without knowing what data the observer specifically needs, and without the means, simply pass itself to the observer and let the Observer take the value as needed.

The push model may make the observer object difficult to reuse, because the Observer's update () method is a parameter that is defined as needed, and may not take into account the unused usage. This means that when new situations arise, it is possible to provide a new update () method, or simply to re-implement the observer, and the pull model does not cause such a situation, because the parameter of the update () method under the pull model is the subject object itself, which is basically the largest set of data that the subject object can pass. Can basically adapt to the needs of various situations.
Java-provided support for the Observer pattern

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.