Java Design Pattern Series (16) Watcher mode (Observer)

Source: Internet
Author: User

Java Design Pattern Series (16) Watcher mode (Observer)

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.

I. Structure of the Observer pattern

    • Subject: A target object that typically has the following functions:

      1. A target can be observed by multiple observers

      2. Target provides maintenance of the registration and unsubscribe of the viewer

      3. When the status of the target changes, the target is responsible for notifying all registered, effective observers

    • Observer: Define the interface of the Observer, provide the Update method corresponding to the target notification, this update method carries on the corresponding business processing, can callback the target object in this method, obtains the target object's data.

    • ConcreteSubject: A specific target implementation object, used to maintain the target State, when the state of the target object changes, notify all registered effective observers, let the observer perform the corresponding processing.

    • ConcreteObserver: The specific implementation object of the observer, which is used to receive notification of the target, and carries out corresponding subsequent processing, such as updating its state to maintain the corresponding state of the target.

A target can have any number of observer objects, and once the state of the target has changed, all registered observers are notified, and the individual observers respond accordingly to the notification, perform the corresponding business function processing, and align their state and the state of the target object.

Source

_(1) Subject

/*** target object, which knows the observer to observe it, and provides an interface for registering and deleting the Observer */ Public classSubject {/*** Used to save the registered observer object     */    PrivateList<observer> observers =NewArraylist<observer> ();/*** Register Observer Object     * @param ObserverObserver Object     */     Public void Attach(Observer Observer) {observers.Add(Observer); }/*** Delete Observer object     * @param ObserverObserver Object     */     Public void Detach(Observer Observer) {observers.Remove(Observer); }/*** Notify all registered Observer objects     */    protected void notifyobservers() { for(Observer observer:observers) {Observer.Update( This); }    }}

_(2) ConcreteSubject

/**   * Specific target object , which is responsible for depositing the relevant state to the corresponding observer object,    public  class  ConcreteSubject extends  Subject {/**   * schematic, status of target object      */ private  String subjectstate; public     String getsubjectstate  () {return  subjectstate; } public  void  setsubjectstate  (String Subjectstate) {this .  = subjectstate;        //state has changed to notify individual observers  this . notifyobservers     (); }}

_(3) ConcreteSubject

/** * 观察者接口,定义一个更新的接口给那些在目标发生改变的时候被通知的对象 */publicinterface Observer {    /**     * 更新的接口     * @param subject 传入目标对象,好获取相应的目标对象的状态     */    publicvoidupdate(Subject subject);}

_(4) ConcreteSubject

/** * 具体观察者对象,实现更新的方法,使自身的状态和目标的状态保持一致 */publicclassimplements Observer {    /**     * 示意,观者者的状态     */    private String observerState;        publicvoidupdate(Subject subject) {        // 具体的更新实现        //这里可能需要更新观察者的状态,使其与目标的状态保持一致        observerState = ((ConcreteSubject)subject).getSubjectState();    }}
Second, the Observer pattern provided by Java

Where Observer and Observable are the packages under Java.util.

(1) ConcreteSubject

publicclassextends Observable {    /**     * 示意,目标对象的状态     */    private String subjectState;    publicgetSubjectState() {        return subjectState;    }    publicvoidsetSubjectState(String subjectState) {        this.subjectState = subjectState;        //状态发生了改变,通知各个观察者        this.setChanged();        this.notifyObservers(subjectState);    }}

(2) Concreteobserver

publicclassimplements Observer {    /**     * 示意,观者者的状态     */    private String observerState;    @Override    publicvoidupdate(Observable o, Object obj) {        //这是采用推的方式        System.out.println("目标推过来的内容是:" + obj);        //这是获取拉的数据        System.out.println("主动到目标对象去拉的内容是:" + ((ConcreteSubject)o).getSubjectState());    }}
Iii. Summary (1) 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 details of the topic to the viewer, regardless of whether the viewer needs it, the information that is pushed is usually all or part of the data for 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 to the observer through the update () method, which can be obtained by this reference when the observer needs to obtain the data.

Record a little bit every day. Content may not be important, but habits are important!

Java Design Pattern Series (16) Watcher mode (Observer)

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.