Void值作为返回参数

dfa*_*dfa 11 java command adapter

我有这个界面:

public interface Command<T> {
    T execute(String... args);
}
Run Code Online (Sandbox Code Playgroud)

它适用于大多数用途.但是当我尝试模拟一个只有副作用的命令(例如没有返回值)时,我很想写:

public class SideEffectCommand implements Command<Void> {

    @Override
    public Void execute(String... args) {
        return null; // null is fine?
    }
} 
Run Code Online (Sandbox Code Playgroud)

这是个常见的问题吗?是否有模型的最佳实践Commands无返回值?

我试过这个适配器,但我认为这不是最佳的,原因如下:

public abstract class VoidCommand implements Command<Void> {

    @Override
    public Void execute(String... args) {
       execute2(args);
       return null;
    }

    public abstract void execute2(String... args);
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ine 10

我会坚持Void明确使用.没有其他课程,很容易看到发生了什么.如果您可以Void使用void(和Integer使用int等)覆盖返回,那将是很好的,但这不是优先事项.


Joh*_*eek 4

这是一个多方面最佳的实现。

// Generic interface for when a client doesn't care
// about the return value of a command.
public interface Command {
    // The interfaces themselves take a String[] rather
    // than a String... argument, because otherwise the
    // implementation of AbstractCommand<T> would be
    // more complicated.
    public void execute(String[] arguments);
}

// Interface for clients that do need to use the
// return value of a command.
public interface ValuedCommand<T> extends Command {
    public T evaluate(String[] arguments);
}

// Optional, but useful if most of your commands are ValuedCommands.
public abstract class AbstractCommand<T> implements ValuedCommand<T> {
    public void execute(String[] arguments) {
        evaluate(arguments);
    }
}

// Singleton class with utility methods.
public class Commands {
    private Commands() {} // Singleton class.

    // These are useful if you like the vararg calling style.
    public static void execute(Command cmd, String... arguments) {
        cmd.execute(arguments);
    }

    public static <T> void execute(ValuedCommand<T> cmd, String... arguments) {
        return cmd.evaluate(arguments);
    }

    // Useful if you have code that requires a ValuedCommand<?>
    // but you only have a plain Command.
    public static ValuedCommand<?> asValuedCommand(Command cmd) {
        return new VoidCommand(cmd);
    }

    private static class VoidCommand extends AbstractCommand<Void> {
        private final Command cmd;

        public VoidCommand(Command actual) {
            cmd = actual;
        }

        public Void evaluate(String[] arguments) {
            cmd.execute(arguments);
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

通过此实现,客户端可以讨论Command是否不关心返回值,以及ValuedCommand<T>是否需要返回特定值的命令。

不直接使用的唯一原因是您将被迫插入Void所有难看的语句。return null;