7 The difference between the observer and the listener in the design pattern

Source: Internet
Author: User
Tags call back event listener sleep wrapper
One of the GOF design patterns is called the Observer Pattern (Observer), which belongs to the behavioral pattern. Also called publish-subscribe (publish/subscribe) mode, model-view (model/view) mode, source-listener (Source/listener) mode, or 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. http://zoroeye.iteye.com/blog/2100318

The observer pattern is called the Queen in the pattern, and the Java JDK implements it, which shows the important position of the design pattern. In the graphical design of the software, in order to achieve the separation of view and event processing, most of the use of observer mode, such as the Java Swing. There are many applications in real-world applications, such as the spring Framework's initialization, which triggers a lot of events, and listeners can react to events they subscribe to.

The JDK not only provides the observable class, the observer interface to support the observer pattern, but also provides the EventObject class, EventListener interface to support the event listening mode, although both belong to the same type mode, belong to the callback mechanism, the initiative to push the message, But there are some differences in usage scenarios.

1. Event-Monitoring mechanism
The event source passes the wrapper of the event to the listener, and when the event source fires the event, the listener receives a method that the event object can call back the event.


2. Observer mode
The Observer (Observer) is equivalent to the event listener (listener), the Observer (Observable) is the equivalent of the event source and event, and when the logic is executed, the Observer is triggered to trigger the Oberver update, and the observers and parameters can be transmitted. simplifies the implementation of event-listening mode.


3. Contrast

(1) from the UML diagram can also be seen, observer implementation is relatively simple, event-listener need to implement three roles, observer-observable need to implement two roles.

(2) Observable API has been the registration of the Observer, delete, listener queue, notification methods are defined, and is thread-safe. and Event-listener need to be implemented by users themselves.

(3) Both need to define themselves and implement notification of triggering events. However, observable needs to be aware that the setchanged () provided by the JDK will be called before notifying Observer.

(4) Event-listener is the traditional C/S interface event model, the event source and the event (status) role, the event source to pass through the event wrapper, the property of the event is repeatedly passed to the event listener/handler, the event listener is the equivalent of the observer. Observer more concise. The two are unified in their minds, and many frameworks still use event-listener patterns, such as the applicationevent,applicationlistener of the spring framework.



The Observer pattern implemented by the JDK-based interface

Observers     class watcher implements java.util.observer {      public void update (java.util.observable obj, object arg)  {       system.out.println ("Update ()  called, count is "                                       +  (Integer)  arg ). Intvalue ());   }   }               //Observer      class beingwatched extends java.util.observable {        void counter (int period)  {            for (; period>=0; period-- )  {        &NBsp;          setchanged ();                     Notifyobservers (New integer (period));                     try {                            thread.sleep (100);                    }  catch ( interruptedexception e)  {                      system.out.println ("Sleep interrupeted"  );                    }            }   }   };      /Demo     public class observerdemo {        public static void main (String[] args)  {            beingwatched beingwatched = new beingwatched ();//Respondents             Watcher watcher = new  Watcher ();//observers             beingwatched.addobserver ( Watcher);            beingwatched.counter (10);        }   }  



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.