Singleton - Creational Design Pattern (II)

8 March 2008

Do read part I of this post. This post is about the implementation of singleton pattern.

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

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;
   }
 }

del.icio.us:Singleton -  Creational Design Pattern (II)  digg:Singleton -  Creational Design Pattern (II)  spurl:Singleton -  Creational Design Pattern (II)  wists:Singleton -  Creational Design Pattern (II)  simpy:Singleton -  Creational Design Pattern (II)  newsvine:Singleton -  Creational Design Pattern (II)  blinklist:Singleton -  Creational Design Pattern (II)  furl:Singleton -  Creational Design Pattern (II)  reddit:Singleton -  Creational Design Pattern (II)  fark:Singleton -  Creational Design Pattern (II)  blogmarks:Singleton -  Creational Design Pattern (II)  Y!:Singleton -  Creational Design Pattern (II)  smarking:Singleton -  Creational Design Pattern (II)  magnolia:Singleton -  Creational Design Pattern (II)  segnalo:Singleton -  Creational Design Pattern (II)  gifttagging:Singleton -  Creational Design Pattern (II)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Singleton - Creational Design Pattern (II)

Leave a Reply