我猜这是某种设计模式问题。
我想将几个操作(输入 + 处理逻辑 + 输出)建模为实现某些 IOperation 接口(interface)的类。
每个操作可能有不同的输入参数和不同的输出参数。
我可以使用每个操作的构造函数为每个操作指定不同的输入。
但我也想以正交方式为每个类获得不同的输出,而不必将接口(interface)转换为具体类。
显而易见的方法是 [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;
}
}
最佳答案
看起来你可以使用 double dispatching .
您不返回值(即 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);
}
}
更新:例如,对于您新编辑的代码,您可以编写:
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);
}
}
关于java - 如何在Java中抽象出不同的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23565632/