不要太严格,这是我对这段代码的解释。让我们称反应流的所有者为 Roland。
起初,Roland 需要一个通用接口inboundSignals
static interface Signal {};
ConcurrentLinkedQueue<Signal> inboundSignals = new ConcurrentLinkedQueue<Signal>();
像Cancel
,Subscribe
和Send
总是具有相同目的的信号是不可变的并且非常频繁地出现,因此将它们实现为Joshua Bloch 的 Singleton是个好主意:
enum Cancel implements Signal { Instance; };
enum Subscribe implements Signal { Instance; };
enum Send implements Signal { Instance; };
另一种方法类似于你的建议和我最喜欢的:
enum CommonSignals implements Signal{
Cancel {
@Override
void debug() {
System.out.println("Cancel");
}
},
Subscribe {
@Override
void debug() {
System.out.println("Subscribe");
}
},
Send {
@Override
void debug() {
System.out.println("Send");
}
};
abstract void debug();
[...] some other methods I could need in the future
}
如您所见,这是一个不同的实现。但想法是一样的 - Signal as singleton
我们继续前进并找到这段代码:
static final class Request implements Signal {
final long n;
Request(final long n) { // every Request has different value of n
this.n = n;
}
};
由于inboundSignals
可以包含多个Request
对象,因此无法将这种类型的 Signal 实现为 Singleton。因此它不能CommonSignals
成为enum
.
结论
Roland 使用了多种可能性中的一种来实现单例。我认为这更多的是一个品味问题。