这更像是一个风格问题,而不是“我遇到麻烦的问题”。对于 Null 占位符对象(我是否使用了正确的术语?),通常首选使用 Singleton 模式吗?为了便于讨论,这里举个例子:
public interface Foo {
void myMethod();
}
public class RealFoo implements Foo {
void myMethod() { /* Do something productive */ }
}
public class MyUniverse {
public static void main(String args[]) {
Foo[] fooArray = new Foo[10];
// do something productive that might result in Null objects in the array
for (Foo f : fooArray) {
f.myMethod(); // I DONT WANT TO DO if (f != null) blah blah
}
}
}
好的,这就是我的情况,是首选做A还是做B?
// A
public class NullFoo implements Foo {
public NullFoo() {}
public void myMethod() { /* don't need to do anything */ }
}
// B
public class NullFoo implements Foo {
private static NullFoo _instance = null;
protected NullFoo() {}
public static NullFoo getInstance() {
if (_instance == null) _instance = new NullFoo();
return _instance;
}
public void myMethod() { /* don't need to do anything */ }
}
谢谢!我的直觉认为 B 几乎总是优越的,但也许我错过了什么,所以我问......