我的想法表明,我有两个类的通用代码,我应该使之成为一个由于干规则(不要重复自己)。
class LongPersistence {
public void storeSomeNiceNumber(@NotNull Long l) {
if (l < 0) {
throw new RuntimeException("value should not be negative");
}
someNicePersistence.store(new String(l).getBytes());
}
}
public Long retrieveSomeNiceNumber() {
try {
byte[] bytesRepr someNicePersistence.retrieve();
Long value = Long.parseLong(new String(bytesRepr));
return value;
} catch (SomeNicePersistenceException e) {
return 0L;
}
}
}所以我开始工作..。
class Persistence<N extends Number> {..。失败的原因是:
我认为在定义良好的语言中,这应该是可能的,正如我到目前为止一直在考虑的那样。我是不是遗漏了什么?请建议如何使此算法对Long和Integer通用(并作为任意数字的A+任务)。
发布于 2020-12-02 18:37:06
由于@VGR,我了解到我需要java.lang.Number类的数学逻辑,它的目的是将数字仅存储为对象(类似于变体类型),因此我已经将数学具体化到另一个接口,在我看来,这更有意义。
public interface NumberMath<E extends Number> {
E parse(String string);
String toString(E e);
E zero();
int signum(E e);
}
class NumberPersistence<E extends Number> {
private final NumberMath<E> math;
private final SomeNicePersistence someNicePersistence;
public NumberPersistence(NumberMath<E> math, SomeNicePersistence persistence) {
this.someNicePersistence = persistence;
this.math = math;
}
public void storeSomeNiceNumber(E l) {
if (math.signum(l) < 0) {
throw new RuntimeException("value should not be negative");
}
someNicePersistence.store(math.toString(l).getBytes());
}
public E retrieveSomeNiceNumber() {
try {
byte[] bytesRepr = someNicePersistence.retrieve();
E value = math.parse(new String(bytesRepr));
return value;
} catch (SomeNicePersistenceException e) {
return math.zero();
}
}
}我把E限制为数字,但老实说,在这种情况下,它不再是必需的。
https://stackoverflow.com/questions/65106773
复制相似问题