Callback/Command vs EventListener/Observer Pattern

Command, callback and observer patterns have different semantics:

  • callback - notifies a single caller that some operation finished with some result
  • observer - notifies zero to n interested parties that some event (for example a finished operation) happened
  • command - encapsulates a operation call in an object thus making it transferable over a wire or persist-able

In your example you could combine both callback and observer patterns to achieve greater API flexibility:

  1. Use the callback pattern to trigger operations and notify the caller asynchronously that the triggered operation finished.
  2. Use the event/observer pattern to give some other components (that did not trigger the operation) the chance to be notified when an operation finishes.

Both patterns are great and which one to choose depends on what are you going to build and how your framework will be used.

If you are trying to build some kind of publish-subscribe system with following typical flow of work:

  • client starts async task and forgets about it
  • multiple handlers receives notifications when task is completed

then Observer pattern is a natural choice for you. As you are doing a framework you should also consider using EventBus pattern to achieve loose coupling.

If you need nothing more than a simple asynchronous execution and a typical flow using of your framework is:

  • start async task
  • do something when it is completed

or

  • start async task
  • do something
  • wait till it is completed and do something

then you should go with simple Callback.

But in order to achieve more usable and clean API I'd recommend you to get rid of Callback abstraction and design your worker code to return a some kind of Future.

public interface Worker<T> {

    Future<T> doAsync();

}

And Worker can be used following way:

Future<Integer> future = worker.doAsync();

// some work here

Integer result = future.get(); // waits till async work is done

Future could be a standard java Future. But I'd suggest you to use ListenableFuture from guava library.