Search code examples
javadesign-patternsgwtguiceservice-locator

Guice-style service locator


Has anybody ever seen/attempted to write a service locator pattern which uses a Guice style configuration system?

Currently I have a GWT project (which happens to use GWT-RPC) that uses a command pattern wherein my RPC servlet that looks like this...

public interface TransactionService extends RemoteService {

    <T extends Response> T execute(Action<T> action);
}

In my current implementation of the execute method I do this...

if(action instanceof SomeActionImpl){
  doSomeActionImpl((SomeActionImpl)action);
}else if(action instanceof SomeActionImpl2){
  doSomeActionImpl2((SomeActionImpl2)action);
}

What I would like to do is figure out a way to get rid of the giant if statement. I would need some way of registering that ActionImpl1's class should be delegated to another implementation of TransactioNService.

Any ideas? I was thinking of just adding entries to a HashMap where the key is the Action's class and the value is the ServiceImpl's Class. One I have a reference to the ServiceImpl class I could use Guice to get an instance of TransactionService.


Solution

  • Take a look at the net.customware.gwt.dispatch.server.DefaultActionHandlerRegistry class in gwt-dispatch (http://code.google.com/p/gwt-dispatch/); it does exactly what you are suggesting. Here is the member variable that stores the handlers:

    private final Map<Class<? extends Action<?>>, ActionHandler<?, ?>> handlers;

    If you want to execute the handlers on the server side, then use the gwt-dispatch server-side components; if it's client-side stuff, then consider modelling your dispatching class on DefaultActionHandlerRegistry.