I'm attempting to decouple some UI code using interfaces and events, and I would like to know if there is way/best practice in Java for declaring an event as part of a Java interface - something like what C# provides:
// C# event declaration in interface
public interface IAction
{
event EventHandler OnAction;
}
My goal is simply to mark an interface so that it is known it (implementors) fires events of a particular type. I'm hoping I can include more than documentation only to enforce that behaviour. I realize Java does not provide the "event" keyword or a direct way of doing this, so I'm hoping for some advice on a workaround or best practice on achieving this.
One way I can think of doing this is by creating a generic marker interface that represents the capability to fire events:
public interface FiresEvent<T extends Event> {
public void fireEvent();
}
... and then to inherit that interface in my custom interface.
public interface MyInterface extends FiresEvent<ActionEvent> {
}
The problem with this approach is that "FiresEvent" can only be inherited once, even if the generic type changes, so the solution does not seem generic enough for the case where an object may be the source of multiple events.
I'd be curious to know how people would handle this, and if there is a better way than to just document the need to fire events.
EDIT: Maybe the following will clear up my question:
I understand the Java handler list approach and self-handling by allowing callers to register handlers against an object. In my case I am relying on an event bus, so we can view "firing" events as putting them out there, for something else to redirect to handlers.
I'd like to define the interface responsibility as:
Java handles events a bit differently than what you're used to, however the concept is the same. You create what's called an event listener, and it's called when the event happens. This can be a better construct as it allows for multiple listeners to be registered.
I suggest browsing this tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With