View RSS Feed

My Java Tips

Singleton - Creational Design Pattern

Rate this Entry
by , 11-20-2011 at 06:14 PM (1306 Views)
The Singleton Design Pattern is the most commonly used design pattern in Java. The Singleton Design Pattern is a Creational Design Pattern. It governs the instantiation process. Sometimes in programming only one object is required across the system. The Singleton Design Pattern is used to achieve exactly that, that is to restrict instantiation of a class to one object. The Singleton Design Pattern ensures a class has only one instance, and provides a global point of access to it.


Several design patterns such as Abstract Factory, Builder, and Prototype can in turn use the Singleton Design Pattern in their implementations. In fact facade objects are often Singleton as only one facade instance is required. If in the future you require multiple instances, with the Singleton design pattern you can achieve that without affecting a singleton class's clients. Some times Singletons are used ahead of global variables.



Implementation

To prevents the direct instantiation of the object by other classes the class’s default constructor is made private. As a result the object cannot be instantiated any other way. The class has a static reference to the only singleton instance and returns that reference from the static method. However in multi threaded applications the singleton pattern must be properly implemented.

The example below demonstrates the use of The Singleton Design Pattern. It uses methodology known as lazy instantiation to create the singleton. Note that the class implements a private constructor so clients cannot instantiate objects of it. The singleton instance is not created until the getInstance() method is called for the first time. This methodology makes sure that singleton instances are created only when needed.

Example

Java Code:
public class Singleton {
   // Note private constructor
   private Singleton() {}

   private static class SingletonInner {
     private final static Singleton instance = new Singleton();
   }

   public static Singleton getInstance() {
     return SingletonInner.instance;
   }
 }

Submit "Singleton -  Creational Design Pattern" to Facebook Submit "Singleton -  Creational Design Pattern" to Digg Submit "Singleton -  Creational Design Pattern" to del.icio.us Submit "Singleton -  Creational Design Pattern" to StumbleUpon Submit "Singleton -  Creational Design Pattern" to Google

Comments