Singleton !! … singleton ??
Table of Contents
Singleton !! … singleton ?? #
Look at this singleton implementation :
public class MyClass {
public static MySingleton singleton;
static {
singleton = new MySingleton() {
@Override public String getSomeField()
{
// my implementation
}
};
}
}
What caught my eye was not the slightly modified singleton pattern (eager initialization) usage but the inline method overriding of a MySingleton to avoid a new class creation (let’s say MyExtendedSingleton) that extends MySingleton and overrides the method getSomeField to create, in the static block, a unique instance of MyExtendedSingleton, right ?
Sadly this is untrue : if MySingleton class is to be extended and method getSomeField overridden to create just one instance, the singleton instance, what’s the point in the override ? why not just replace the getSomeField in the class MySingleton with the one overriden ? why to reuse if there’ll be just one usage ?
Looking at the original code I discovered a bug because the MySingleton class is not in the same file as MyClass, then the constructor which allows creation of more than one instance (if the constructor is private can’t be accessed from outside the class then the singleton mechanism must be implemented in the class MySingleton).
There’s one exception, and is the case when MySingleton behavior needs to be slightly different and used as a singleton, meaning that the common behavior is located in a base (abstract) class that is extended for the classes that will be implemented as singletons. Enjoy!