In some cases, we need to expose a shared resource throughout the application e.g. DB connection but we don't want to
- create shared object up-front (before creation of client objects).
- explicitly pass shared object to each client object.
then we can use Singleton design pattern.
Typical Singleton class looks like
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
But we can achieve the similar behaviour by making each and every instance methods which are exposing business operation as static. In this approach we don't even need to create single object.
Then why do we need Singleton?
Well, the answer is simple. To isolate actual implementation from the client. Basically we are applying abstraction OOP principle here.
This is helpful If the singleton class is part of library which is used by various clients and library wants to vary the implementation as per the client.
Sample for such singleton can be
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingletonChild(); // here we are creating an object of subclass of MySingleton.
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
Hope this help in understanding Singleton design pattern.