This is more of a style question than an "I'm having trouble question". For Null placeholder objects (am I using the right term?), is it generally preferred to use the Singleton pattern? For ease of discussion, here's an example:
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
}
}
}
Ok so that's my scenario, is it preferred to do A or 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 */ }
}
Thanks! My instinct that B is almost always superior but maybe I'm missing something, so I ask...
Foo[] fooArray = new Foo[10];