【发布时间】:2018-05-02 18:52:54
【问题描述】:
我有一个接口Operations:
public interface Operations{
Operations add(Operations op);
Operations subtract(Operations op);
}
这个界面应该允许用户选择如何进行简单的计算。例如,如果用户只想使用数据类型Integer 及其基本操作,他可以使用类MyInteger:
// simple implementation without type check etc..
public final class MyInteger implements Operations{
private final int delegate;
public MyInteger(int i){
delegate = i;
}
@Override
Operations add(Operations other){
return new MyInteger(delegate + ((MyInteger) other).delegate);
}
@Override
Operations subtract(Operations other){
return new MyInteger(delegate - ((MyInteger) other).delegate);
}
(...)
}
在其他类中,将根据接口Operations 的功能进行计算。但有时我需要一个静态上下文,如 valueOf(val) 函数,它为给定的 String、double、int 等返回相应类的实现,如下例所示:
public class Calculation<D extends Operations> {
private final D value1, value2;
private final D value3 = D.valueOf(4); // cannot implement this in interface
public Calculation(D value1, D value2){
this.value1 =value1;
this.value2 = value2;
}
public D sumPlusValue3(){
return value1.plus(value2).plus(value3);
}
}
所以
Calculation<MyInteger> calc = new Calculation<MyInteger>(new MyInteger(1), new MyInteger(2));
Operations result = calc.sumPlusValue3();
一般来说,我认为我必须使用像 Builder 或 Factory 这样的设计模式来允许用户指定他想要的实现,比如
Operations integerImpl = OperationsBuilder.create("Integer");
但在研究了这些模式之后,我也找不到一种干净的方法来在Calculation 类中为value3 实现泛型类D。
编辑 1:
我编辑了问题并标记了来自@Stefan Haustein 的答案,因为这是解决我的问题的最佳方法。
但@davidxxx 的回答也是关于我最初的问题的一个很好的回答 - 如何only 表示valueOf(int val) 函数。
【问题讨论】:
-
我想在
double中添加int,可以吗?考虑Operation<OPERAND1, OPERAND2, RESULT> -
不,这应该是不可能的。这意味着必须验证所有操作实现都属于同一实例。在 Calculations 类中,这是因为泛型参数而满足的,或者?
标签: java generics design-patterns interface