简体   繁体   中英

General return type - Java

My question is based around invoking a server method by using the command pattern. However there are many possible commands. I would like to introduce a return type for the 'execute' method of each command instance. I know this is not the intended use of the command pattern, but I haven't any other choice. I need to tailor the command pattern to work for me.

For the method signature of the 'execute' method in each command, what could I possibly have as the return type? I'm guessing it would have to be a covariant return type. It's not an ideal solution but I haven't many other options. I'm developing a server for my android app and RMI isn't available in the Android SDK. I would appreciate any advice about the return type issue. I would need to take account of all of the return types that could be returned from all of the different commands. I'm not sure if there is a pattern out there for this issue of returning some sort of generic return type.

I have already looked at this thread: command pattern returning status but I need more inspiration.

I probably don't understand the real question here, but this sounds straightforward.

public interface Command<T> {
  T execute();
}

And then teh commands could be:

public class FooCommand implements Command<Bar> {

  public Bar execute() {
    ...
  }
}

Or is there a catch somewhere?

It looks like what you really want is RMI, which Android doesn't support.

You can try to use a lightweight RMI.

To implement something yourself, start from biziclop's interface,

// suppose there are object input/output streams established

// on client side
FooCommand foo = new FooCommand(params..);
Bar bar = remoteExec( foo );

<T> T remoteExec(Command<T> cmd)
     output.writeObject(cmd);
     return (T)input.readObject();

// on server side

    Command cmd = (Command)input.readObject();
    Object result = cmd.execute();
    output.writeObject(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM