【发布时间】:2014-04-23 14:02:40
【问题描述】:
我遇到的问题之前已经有人问过了:How to implement an interface with an enum, where the interface extends Comparable?
但是,没有一个解决方案可以解决我的确切问题,即:
我有一个值对象,类似于BigDecimal。有时该值不会用真实对象设置,因为该值尚不知道。所以我想用Null Object Pattern 来表示这个对象没有定义的时间。这一切都不是问题,直到我尝试让我的 Null 对象实现 Comparable 接口。这是一个 SSCCE 来说明:
public class ComparableEnumHarness {
public static interface Foo extends Comparable<Foo> {
int getValue();
}
public static class VerySimpleFoo implements Foo {
private final int value;
public VerySimpleFoo(int value) {
this.value = value;
}
@Override
public int compareTo(Foo f) {
return Integer.valueOf(value).compareTo(f.getValue());
}
@Override
public int getValue() {
return value;
}
}
// Error is in the following line:
// The interface Comparable cannot be implemented more than once with different arguments:
// Comparable<ComparableEnumHarness.NullFoo> and Comparable<ComparableEnumHarness.Foo>
public static enum NullFoo implements Foo {
INSTANCE;
@Override
public int compareTo(Foo f) {
return f == this ? 0 : -1; // NullFoo is less than everything except itself
}
@Override
public int getValue() {
return Integer.MIN_VALUE;
}
}
}
其他问题:
- 在实际示例中,这里有多个我称之为
Foo的子类。 - 我可以通过让
NullFoo不是enum来解决这个问题,但是我不能保证只有一个实例,即Effective Java Item 3, pg. 17-18
【问题讨论】:
-
我不喜欢 NullObject 模式。尤其是因为它会把你引向这种东西。在您的程序中比较 NullObject 表示的未初始化对象是否有意义?
-
@Joffrey 这不是“未定义”,而是语义上的“零”。虽然这样想可能是解决这个问题的正确方法……"Once a problem is described in sufficient detail, its solution is obvious"
-
我想用空对象模式来表示这个对象没有定义的时间。 -- 好吧,我以为你的意思是 undefined .但无论如何,
Zero不是null,也不是NullObject。你的班级是什么类型的?当它不是“null”时它应该代表什么?你说类似于 BigDecimal,所以我假设它是数字? -
@Joffrey 这是一个逐渐更新的值,但它从零开始是一个合理的初始值。 undefined 不是正确的词,uninitialized 更好。
-
好吧,你提出了 undefined,其实我自己也使用过 non-initialized ^^ 所以我的意思是,实际上是否有意义在比较中使用未初始化的对象?如果您希望它在语义上为 0,并且表现得如此,那么为什么不使用普通对象的 0 值呢?如果你以后需要它,你可以有一个标志说它没有被初始化。
标签: java enums comparable null-object-pattern