Observer Mode (OBSERVER)

Source: Internet
Author: User

Objective:
The Observer (Observer) pattern is the behavior pattern of an object, also known as a publish-subscribe pattern, model-view mode, source-listener mode, or dependent-person 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. This subject object is changed in state, and will let all the observer objects be notified that they can automatically update themselves.
(i) A brief picture of the Observer pattern:

(ii) Environmental role of the observer model
Abstract theme (Subject) role: The subject role holds all references to the Observer object in a cluster (such as a vector object), each subject can have any number of observers.
Abstract observer (Observer) Role: Define an interface for all specific observers, and update yourself on the notification of getting the subject.
Specific subject (ConcreteSubject) role: The status of the State is deposited into the specific observer object, and all registered observers are notified when the internal state of the specific subject changes.
Specific observer (Concreteobserver) Role: Stores the status of the theme with its own state.
(c) Sample source code:
Abstract theme (Subject) role:

package  Com.observer;public  interface  subject  { /** * Call this method to register a new observer object * @param  Observer */ public      void  attach  (Observer Observer);     /** * Call this method to delete an already registered observer object * @param  Observer33 */ public  void  detach     (Observer Observer);    /** * Call this method to notify all registered Observer objects */ void  notifyobserver ();}  

Abstract Viewer (Observer) Role:

package com.observer;publicinterface Observer{    /**     * 调用这个会更新自己     */    void update()}

Specific theme (ConcreteSubject) roles:

 PackageCom.observer;ImportJava.util.Enumeration;ImportJava.util.Vector; Public  class ConcreteSubject implements Subject{    PrivateVector observersvector=NewVector ();/** * Call this method to register a new Observer object */     Public void Attach(Observer Observer)    {observersvector.addelement (Observer); }/** * Call this method to delete an already registered Observer object */     Public void Detach(Observer Observer)    {observersvector.removeelement (Observer); }/** * Notifies this method to notify all registered Observer objects * @return  * *     Public void  Notifyobserver() {enumeration enumeration=observers (); while(Enumeration.hasmoreelements ())        {((Observer) enumeration.nextelement ()). Update (); }    } PublicEnumerationobservers()    {return(Vector) Observersvector.clone ()). elements (); }}

Specific observer (CONCRETEOBSERVER) role:

package com.observer;publicclass ConcreteObserver implements Observer{    /**     * 调用这个方法会更新自己     */    publicvoidupdate()    {        System.out.println("I am notified");    }}

Four Observer in the JDK
Observer interface

Source
Abstract Viewer (Observer) Role:

package java.util;publicinterface Observer{    /**    *调用这个方法会更新自己    */    void update(Observable o, Object arg);}

Java.util.Observable class
Abstract subject Class (Observer)

 PackageJava.util; Public  class Observable {    Private BooleanChanged =false;PrivateVector Obs;/** Construct An Observable with zero observers. * *     Public Observable() {Obs =NewVector (); }/** * Add an observer to the Observer's aggregation * *     Public synchronized void Addobserver(Observer o) {if(O = =NULL)Throw NewNullPointerException ();if(!obs.contains (O))        {obs.addelement (o); }    }/** * Remove an observer object from the Observer aggregation */     Public synchronized void Deleteobserver(Observer o)    {obs.removeelement (o); }/** * equivalent to Notifyobserver (NULL) */     Public void notifyobservers() {Notifyobservers (NULL); }/** * If the object changes (at that time the Haschannged method returns True) * Call this method to notify all registered observers, call their update () method * Pass in this and arg as parameters */     Public void notifyobservers(Object Arg) {/ * * Temporarily store the status of the current observer, see Memo mode */Object[] arrlocal;synchronized( This) {if(!changed)return;            arrlocal = Obs.toarray ();        Clearchanged (); } for(inti = arrlocal.length-1; i>=0; i--) ((Observer) arrlocal[i]). Update ( This, ARG); } Public synchronized void deleteobservers() {obs.removeallelements (); }protected synchronized void setchanged() {changed =true; }protected synchronized void clearchanged() {changed =false; } Public synchronized Boolean hasChanged() {returnChanged } Public synchronized int countobservers() {returnObs.size (); }}

Each observer is an object that implements the Observer interface. When the object of the observer changes, he invokes observable's Notifyobservers method, which invokes the update () method of all the specific observers, so that all observers are notified to update themselves.
The call example diagram is as follows:

(v) Application scenarios for observer patterns
1. Updates to an object state require other objects to be updated synchronously, and the number of other objects is dynamically variable.
2. Objects only need to notify their own updates to other objects without needing to know the details of other objects.
(vi) Observer pattern Yes pros and cons
Advantages
1) The Observer pattern creates an abstract coupling between the observer and the Observer. What is known by the observer role is a gathering of specific observers, each of which conforms to the interface of an abstract observer. The observer does not know any specific observer, it only knows that they all have a common interface. Because the observer and the observer are not tightly coupled, they can belong to different levels of abstraction.
(2) Observer mode supports broadcast communication. The observer will give notice to all the registered observers.
The observer pattern has some of the following drawbacks :
(1) If an observer object has many direct and indirect observers, all observers are informed that it will take a lot of time.
(2) If there is a cyclic dependency between the observers, the observed will trigger a cyclic call between them, causing the system to crash. Pay special attention to this when using the observation mode.
(3) If the notice to the Observer is asynchronous delivery via another thread, the system must ensure that the delivery is carried out in a self-consistent manner.
(4) Although the observer pattern can always make the observer aware that the object being observed has changed, the Observer pattern does not have a mechanism for the observer to know how the observed object has changed.
Reference "Java and Patterns"
"Head First design mode"

Observer Mode (OBSERVER)

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.