Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an EventListener in contrast to an EventHandler? [closed]

How can I implement one? Will it work across multiple assemblies? If not, how can I make it work?

like image 731
DaveDev Avatar asked Dec 09 '22 22:12

DaveDev


1 Answers

At the risk of not understanding the question fully, I would like to offer another possible explanation.

Talking about classes, Java has an EventListener and .NET has an EventHandler. Both have the same purpose: event handling. However there are differences in implementation. It could be said that .NET's event handling is a higher level of abstraction to Java's event listeners.

The Java's EventListener is "a tagging interface that all event listener interfaces must extend" (i.e. MouseListener). The .NET's EventHandler is a delegate, a strongly typed pointer to a method that handles an event.

More broadly, an event listener is an object that implements an interface for event handling while an event handler is just a method that handles an event. Generally speaking, event listeners implements an Observer Design Pattern and event handlers hide all the plumbing of that pattern. Therefore writing an event listener is much more involved and tends to be more verbal than writing an event handler.

I would recommend to read the Observer Design Pattern by Microsoft to get a better understanding of it.

So, to implement an event handler you simply assign a delegate to the event of an object you want to handle. I.e.

Button.Click += new EventHandler(MyButton_Click); 

where MyButton_Click is a method (it could be in your class or somewhere else) that has the EventHandler's signature and actually handles the event, i.e.

private void MyButton_Click(object sender, EventArgs e)
{
    doSomething();
}

To achieve the same with event listeners in Java, you would write something like this (pardon me if I'm making mistakes, since I'm writing it from memory):

public class MyClass
{
    Button myButton;

    MyClass()
    {
        ...
        myButton.addMouseListener(new ButtonHandler());
    }

    public class ButtonHandler implements MouseListener
    {
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}

        public void mouseClicked(MouseEvent e)
        {
           doSomething("Mouse clicked", e);
        }
    }
}

Naturally, there are many ways to implement this common observer pattern, including implementing EventListener interfaces in the class itself, in inner classes, in anonymous classes, in adapters, etc. But this should demonstrate the point.

like image 151
Ruslan Avatar answered May 16 '23 06:05

Ruslan