Sunday, August 5, 2012

Though personally I am not too much in favor of singletons but its a good brain exercise to see different ways in which it could be implemented.

The standard way as we all know is you have a final class (ideally purely for performance optimizations) with a private constructor and a public static getter method. I personally like to create the singleton object eagerly. It saves all the hassles to keep the getter method synchronized and therefore, make it a lot more scalar.

With the advent of generics, their application with different data structures and design patterns evolved and so did a couple of variants of Singleton.

class GenericSingleton {

private static final GenericSingleton instance = new GenericSingleton();
private GenericSingleton(){ }
public static GenericSingleton getInstance()
{
return (instance);
}
}

There is one more way to implement this and that being creating a map of identifiers and their classes but personally i prefer the above way as i prefer casting being kept out of the singleton itself.