Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the role of java's listener mode and observer, respectively?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the role of java's listener mode and observer respectively". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the role of java listener mode and observer respectively?"

1. Java.util.Observer-corresponding to the Observer API:

Java.util.Observable-the root class of the respondent

2. Java.util.EventListener-- corresponding to event listening / handling APIs:

Java.util.EventObject-event (state) object root class

After a study, it is found that the purpose and function of the two interfaces are actually the same (only slightly different in the structure of the event model). Let's first take a look at the EventListener event listener mode:

/ / https://blog.csdn.net/sbvfhp/article/details/8763896// java design pattern-Observer pattern and event listener pattern / / first define the event source object (the event source is equivalent to the button object in the button-clicked event and belongs to the listener) public class DemoSource {private Vector repository = new Vector () / / listen to your own listener queue public DemoSource () {} public void addDemoListener (DemoListener dl) {repository.addElement (dl);} public void notifyDemoEvent () {/ / notify all listeners Enumeration enum = repository.elements (); while (enum.hasMoreElements ()) {DemoListener dl = (DemoListener) enum.nextElement () Dl.handleEvent (new DemoEvent (this));} / / then define the event (state) object (this event object wraps the event source object and passes it as a parameter to the listener, a very thin wrapper class) public class DemoEvent extends java.util.EventObject {public DemoEvent (Object source) {super (source) / / source- event source object-such as a button in a button-click event that occurs on the interface / / all Event references the object "source" when constructed, which is logically considered to be the object that originally occurred about Event} public void say () {System.out.println ("This is say method..."). }} / / finally, our event listener interface is defined as follows: public interface DemoListener extends java.util.EventListener {/ / EventListener is the tagged interface that all event listener interfaces must extend, because it is a content-free tagged interface, / / so the event handling method is declared by ourselves as follows: public void handleEvent (DemoEvent dm) } / / define specific event listeners: public class DemoListener1 implements DemoListener {public void handleEvent (DemoEvent de) {System.out.println ("Inside listener1..."); de.say (); / / callback}} public class TestDemo {DemoSource ds; public TestDemo () {try {ds = new DemoSource () / / register the listener in the event source object: DemoListener1 L1 = new DemoListener1 (); ds.addDemoListener (L1) Ds.addDemoListener (new DemoListener () {public void handleEvent (DemoEvent event) {System.out.println ("Method come from Anonymous Class...");}}); ds.notifyDemoEvent () / / trigger event, notify listener} catch (Exception ex) {ex.printStackTrace ();}} public static void main (String args []) {new TestDemo ();}}

Let's take a look at the Observer observer mode:

Observer differs from EventListener only in that it declares event handling methods in advance:

Update (Observable o, Object arg)

There is no corresponding EventObject role in the Observer schema, so the observed Observable has both source event source and EventObject event object roles, and the model is more concise.

The Observable observer root class holds the observer queue and defines a notifyObservers () method similar to notifyDemoEvent ().

Apart from the structural differences, you really can't see the difference between the Observer observer mode and the EventListener event monitoring / handling mode! Is there any difference between the two?

Reply:

You can't say that.

I took a look at the jdk source code of Observer and Observable. The Observer interface has nothing to say but declares a update method, which is equivalent to what I defined in the interface DemoListener extends java.util.EventListener interface: the handleEvent method.

Why the statement? The most important thing is that the difference between Observer and EventListener is that most of the work is done in the Observable root class.

I also looked at the Observable root class, although the code is also very short but more concise, at least I can not write such a comprehensive consideration. Like java2 collection, we can do some hashmap, arraylist, stack and team ourselves, but the reliability should not be as reliable as that provided by jdk.

Summarize the main differences between Observer mode and EventListener:

1. The structure of the model is different: EventListener is the traditional event model of the cstroke interface, which is divided into event source and event (state) role. The event source is packaged by the event and passed to the event listener / handler again and again as the attribute of the event. The event listener is equivalent to the observer. I remember as if VB or C # were the same model. On the other hand, the model of Observer pattern is much more concise, there is no distinction between event source and event, the two are combined into one role: the observed should be the same literally, and the other is the observer role.

Second, the difference between the Observer mode I mentioned above and EventListener is that most of the work is classified into the Observable root class implementation, including defining listener queues and notification methods. All we have to do is inherit, invoke and pass values.

Now come to think of it, it is possible that the EventListener snooping mechanism has been inherited from the era of jdk, while the Observer mode and the iterator iterator mode are also integrated into the jdk, so now the two functions of api will exist at the same time.

Also post the Observer mode demonstration code to compare:

/ / Observer 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--) {setChanged (); notifyObservers (new Integer (period)); try {Thread.sleep (100);} catch (InterruptedException e) {System.out.println ("Sleep interrupeted") }; / / demonstrate public class ObserverDemo {public static void main (String [] args) {BeingWatched beingWatched = new BeingWatched (); / / subject Watcher watcher = new Watcher (); / / Observer beingWatched.addObserver (watcher); beingWatched.counter (10);}}

Reply:

Looked up some related things.

It turns out that these two kinds of api can be said to be based on the event / message notification mode of the subscription-publish mode, and both of them should be regarded as "push" mode, in which the monitored notifies all supervisors of the message.

1. Subscription: Observable.addObserver

Event source. AddDemoListener (this method is self-defined).

2. Release: Observable requires two steps: setChanged () and notifyObservers (newValue)

Event source. NotifyDemoEvent () (this method is also self-defined).

Some people say that Observer is the queen of the design pattern, and many system-level implementations are in this way. I think it's confused, because I don't think java.util.Observer 's api has any subordinate interfaces or implementation classes.

Instead, a similar java.util.EventListener has a large number of subordinate interfaces and implementation classes, famously including:

Java.beans.PropertyChangeListener

Javax.servlet.http.HttpSessionListener...

And a lot of api in the java interface.

From this point of view, there are many more EventListener applications than Observer applications. I wonder if it is because EventListener has fewer restrictions and does not specify event handling method names, such as HttpSessionListener defines event handling methods according to its own application domain:

SessionCreated (HttpSessionEvent se) and

SessionDestroyed (HttpSessionEvent se)

If you use Observer, you can only call it update.

Personal understanding is to couple through combination and try not to use inheritance.

Thank you for reading, the above is the content of "what is the role of java listener mode and observer respectively". After the study of this article, I believe you have a deeper understanding of the role of java listener mode and observer respectively, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report