如何在Java中抽象不同的返回类型?

Leo*_*Leo 2 java design-patterns

我猜这是一个设计模式问题。

我想将几个操作(输入+处理逻辑+输出)建模为实现某些IOperation接口的类。

每个操作可以具有不同的输入参数和不同的输出参数。

我可以使用每个构造函数为每个操作指定不同的输入。

但是我也想以正交的方式为每个类获取不同的输出,而不必将接口强制转换为具体的类。

显而易见的方法是[1]强制转换为具体的类并调用返回所需结果的特定方法,或者[2]将结果包装到某些OperationResult对象中,而该对象还需要向下转换或一些元数据信息+提取器代码。

我想避免处理反射或贬低或元数据解释。

Java中是否有针对这种情况的已知设计?有什么好的方法呢?

更新-@Laf,这里有一些具体的例子。我想提取“ c”

interface IOperation{
    void execute();
}

public class AddOp implements IOperation{

    private int a;
    private int b;
    private int c;

    public AddOp(int a, int b){
        this.a = a;
        this.b = b;
    }

    @Override
    public void execute() {
        this.c = this.a + this.b;
    }

}

public class AndOp implements IOperation{

    private boolean a;
    private boolean b;
    private boolean c;

    public AndOp(boolean a, boolean b){
        this.a = a;
        this.b = b;
    }

    @Override
    public void execute() {
        this.c = this.a && this.b;
    }

}
Run Code Online (Sandbox Code Playgroud)

vz0*_*vz0 5

看起来您可以使用双重调度

您不返回值(即Object),而是返回void并将要放入结果的目标对象作为参数传递。

interface ResultProcessor {
    processTypeA(A item);
    processTypeB(B item);
    processTypeC(C item);
}

interface InputProcessor {
    processInput(ResultProcessor target);
}

class ConcreteInputProcessorA {
    processInput(ResultProcessor target) {
      A result = ...; // Do something
      target.processTypeA(result);
    }
}

class ConcreteInputProcessorB {
    processInput(ResultProcessor target) {
      B result = ...; // Do something
      target.processTypeB(result);
    }
}

class ConcreteInputProcessorC {
    processInput(ResultProcessor target) {
      C result = ...; // Do something
      target.processTypeC(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:例如,使用新编辑的代码,您可以编写:

public class AddOp implements IOperation{

    private int a;
    private int b;
    private int c;

    public AddOp(int a, int b){
        this.a = a;
        this.b = b;
    }

    @Override
    public void execute(Executor ex) {
        this.c = this.a + this.b;
        ex.executeAddOp(this);
    }
}

public class Executor {
    public void executeAddOp(AddOp op) {
        System.out.println("Executing an AndOp... " + op);
    }
}
Run Code Online (Sandbox Code Playgroud)