event handling

|

http://docs.oracle.com/javase/6/docs/api/java/util/Observable.html

 

An Observable object has a list of observers which implement the Observer interface, and mechanisms for adding and removing observers. If o.notifyObservers(x) is called on the observable, update(o,x) will be called on each observer. This mechanism is somewhat old fashioned and rarely used in new code - it dates from Java 1.0 before EventObject was added in Java 1.1 and better event handling added for AWT and beans.

 

------------------------------------

 

https://scatteredcode.wordpress.com/2011/11/24/from-c-to-java-events/

Events in C#

The first conceptual hurdle I came across was dealing with Events. In C#, events are pretty easy to deal with, as an event is can be described as a collection of methods that all conform to a single delegate’s method signature. An example of this, based on a good tutorial on Code Project is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
namespace wildert
{
    public class Metronome
    {
        public event TickHandler Tick;
        public EventArgs e = null;
        public delegate void TickHandler(Metronome m, EventArgs e);
        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    Tick(this, e);
                }
            }
        }
    }
     
    class Test
    {
        static void Main()
        {
            Metronome m = new Metronome();
            m.Tick += HeardIt;
            m.Start();
        }
         
        private void HeardIt(Metronome m, EventArgs e)
        {
            System.Console.WriteLine("HEARD IT");
        }
    }
}

This is essentially adding the HeardIt method to the Metronome.Tick event, so whenever the event is fired, it calls theTest.HeardIt() method (along with any other method attached to the event). This is pretty straightforward in my (biased) opinion.

Events In Java

I started reading some pages on the net about how events in Java are handled. The first few articles I came across were kind of confusing and all over the place. I felt like I almost understood how it’s done but I was missing one piece of crucial information that binds it all together for me. After reading a few more articles, I finally had my “Ah ha!” moment, and it all clicked.

The confusion was due to that fact that unlike in C#, there is no event keyword in Java. In fact, and this is the piece I was missing, there essentially is no such thing as an event in Java. In Java you are essentially faking events and event handling by using a standard set of naming conventions and fully utilizing object-oriented programming.

Using events in java is really just a matter of defining an interface that contains a method to handle your event (this interface is known as the listener interface). You then implement this interface in the class that you want to handle the event (this is the listener class). In the class that you wish to “fire off” the event from you maintain a collection of class instances that implements the listener interface, and provide a method so listener classes can pass an instance of themselves in to add and remove them from the collection. Finally, the act of firing off events is merely going through the collection of listener classes, and on each listener call the listener interface’s method. It’s essentially a pure-OOP solution masquerading as an event handling system.

To see this in action, let’s create the equivalent of the C# event example in Java.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.kalldrexx.app
 
// Listener interface
public interface MetronomeEvent {
    void Tick(Date tickDate);
}
 
// Listener implementation
public class MainApp implements MetronomeEvent {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        EventFiringSource source = new EventFiringSource();
        source.addMetronomeEventListener(this); // Adds itself as a listener for the event
        source.Start();
    }
     
    public void Tick(Date tickDate)
    {
        // Output the tick date here
    }
}
 
// Event source
public class EventFiringSource {
 
    // Our collection of classes that are subscribed as listeners of our
    protected Vector _listeners;
     
    // Method for listener classes to register themselves
    public void addMetronomeEventListener(MetronomeEvent listener)
    {
        if (_listeners == null)
            _listeners = new Vector();
             
        _listeners.addElement(listener);
    }
     
    // "fires" the event
    protected void fireMetronomeEvent()
    {
        if (_listeners != null && _listeners.isEmpty())
        {
            Enumeration e = _listeners.elements();
            while (e.hasMoreElements())
            {
                MetronomeEvent e = (MetronomeEvent)e.nextElement();
                e.Tick(new Date());
            }
        }
    }
     
    public void Start()
    {
        fireMetronomeEvent();
    }
}

When the app starts (and enters the MainApp’s main() method), it creates the event source and tells it that the MainApp class should be registered as a listener for the Metronome event. When the event source class starts, it will “fire” off the event by just looking at all classes registered that implement the MetronomeEvent interface, and call the Tick() method for that implemented class.

No special magic, just pure object-oriented programming!

 

In Java 8, the code can be simplified using the lambda, streams, and pipeline features:

if (_listeners != null && _listeners.isEmpty())
{
Enumeration e = _listeners.elements();
while (e.hasMoreElements())
{
MetronomeEvent e = (MetronomeEvent)e.nextElement();
e.Tick(new Date());
}
}

can be changed to

if (_listeners != null)
{
_listeners.parallelStream().forEach(ell -> ell.Tick(new Date()));
}

 

-------------------------------------

 

 

 

---------------------------------------

 

 

 

-----------------------------------------

 

 

 

--------------------------------------

 

 

 

---------------------------------------------

 

 

 

-------------------------------------------

 

 

 

------------------------------------

 

 

 

--------------------------------

 

 

 

-------------------------------------

 

 

 

-------------------------------------

 

 

 

 

 

'개발/활용정보 > Java' 카테고리의 다른 글

ManualResetEvent for Java  (0) 2017.09.07
정규식  (1) 2017.07.05
singleton pattern  (0) 2017.06.29
BundleActivator와 BundleContext  (0) 2014.12.16
guava  (0) 2013.08.08
And