Whenever we need to restrict instantiation of a class to one object, then we use Singleton design Pattern. The Singleton is intended to provide a way to ensure that a class provides one instance of itself, and to provide a global point of access. The Singleton class is responsible for instantiating itself and passing that instance to the client. Therefore, the access modifier for the Singleton constructor must be either private or protected so the client cannot call the constructor itself. The Singleton also provides a method that returns the sole instance of itself to the client. The first time when the client requests an instance, the Singleton will create that instance internally and store it as a private member.
Each subsequent call from the client will return that instance only. Singleton design pattern is useful for controlled access to sole instance, reduced name space, refinement of operations and representation, variable number of instances, greater flexibility than class operations. Let us take an example of Singleton design pattern in Java.
// Implementing Singleton design pattern in Java
public class SampleSingleton {// Private constructor suppresses generation of a (public) default constructor
private SampleSingleton ( ) { }private static class SampleSingletonHolder {
private static SampleSingleton instance = new SampleSingleton ( );
}public static SampleSingleton getInstance( ) {
return SampleSingletonHolder.instance;
}
}
The Singleton class’s default constructor is made private, which prevents the direct instantiation of the object by other classes using the new keyword.
When we should use Singleton design pattern?
If you are designing a system, and you want to control how an object is used and prevent users from making copies of it or creating new instances. Let us take an example of a connection pool. It’s not good to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.
The Singleton pattern is often used with the factory method pattern to create a system wide resource whose specific type is not known to the code that uses it. We use these two design pattern in Abstract Windowing Toolkit (AWT). While designing GUI applications, we always make one instance of a graphical element per application instance, like the Print dialog box or Submit button.
hi abhishek
to add more to this i feel what is singleton is just not enough …fine that its a single object with global access …but the most important thing is like how we create it.We do static initialization ,Lazy initialization ..or we provide some overheads of monitor locks(synchronise) in multithreaded enironments .so it will be more informative if you share all those things also .
Why not make the constructor protected for re-use?