Define the Event interface

You must define an interface to contain your event methods.

The event interface will be:

Note that we are using the word "interface" loosely here. A very important consideration is whether you might ever change the event interface to create additional methods. If you do, all existing implementations of the interface are forced to implement the new methods. In this case, you are strongly advised to use abstract classes rather than Java interfaces. These classes should provide empty implementations of event methods, rather than declare them abstract, so that newly added methods do not cause compilation problems for existing implementations. This approach also means that you can group many related events together in a single abstract class declaration, knowing that only those methods of interest to a particular customer need to be implemented, since default empty implementations for all methods are inherited.

The event interface is typically public so that class in any code package can listen to its events. The interface can be created as an inner interface, in which case it can simply be named Event without fear of name collision with other event interfaces. Typically your entity implementations are package-protected, and so the event interface should be declared as an inner interface of your entity's public interface. However, here for brevity an inner interface is shown declared on the simple class:

Figure 1. Defining the Event interface
          package curam.mypackage;

public class MyEventSource {
           public abstract class Event {
    public void preDoSomething(MyEventSource raiser) {
      // intentionally empty
    }

    public void postDoSomething(MyEventSource raiser) {
      // intentionally empty
    }
  } 
          public void doSomething() {

    // do whatever it is that needs to be done
    System.out.println("Do something!");

  }

}

You must carefully think about the signature of your event methods. The event method is free to pass any number of parameters and/or throw exceptions; note though that the EventDispatcherFactory (see below) ignores any return values, so if you require listeners to return a value then you have to supply your own custom event dispatch logic.

Because each listener is a single instance, typically each event method should pass the instance which raised the event, so that the listener can identify the source of the event. In the example both preDoSomething and postDoSomething take an instance of MyEventSource, namely the instance which raised the event.