How can I implement the command pattern in Java?
I watched "Google Web Toolkit Architecture: Best Practices for Architecting Your GWT App" and I'm having trouble figuring out how the server side is supposed to work.
Slide 21 shows:
/** The name Command is taken */
interface Action<T extends Response> { }
interface Response { }
interface ContactsService extends RemoteService {
<T extends Response> T execute(Action<T> action);
}
interface ContactsServiceAsync {
<T extends Response> void execute(Action<T> action,
AsyncCallback<T> callback);
}
开发者_如何学Python
I thought that meant I might be able to create
public ResponseSubclass execute(ActionSubclass action) { ... }
and gwt would choose that method when it matches my exact parameters, but it doesn't. At the moment i'm using:
if (action.getClass().getName() == ActionSubclass.class.getName())
{
return (T) execute((ActionSubclass)action);
}
but that means I have to keep adding ifs to that method every time I add an action and I have to use unchecked casts. Is there a better way to make this work?
note: from what I have read somewhere else, the command pattern would usually include the actions to be taken in the Ac subclass, but because this is passing a client object for the server take some action on, the execution of the action has to be separated.
Checkout GWT-Dispatch and how to use it here.
As an aside, this may be one of the best articles that references Ray Ryan's IO talk and builds a Hello World app. The application uses GWT-Dispatch.
-JP
I'm using the command pattern in combination with a visitor pattern. This makes it typesafe and easy to extend.
All you need at the server side is a repository of handlers that you can match with the Request object. There are plenty of ways of handling this. Visitor is one way, but you could just base the mapping on naming convention or you could use an inject framework to map the request object to a handler for that type.
It's then down to the server to work out what to do with the action object. As others have said, gwt-dispatch is a good place to look for the server-side part of this story.
精彩评论