Monday 9 June 2014

Singleton Design Pattern in java

Singleton pattern in Java is one of the most common patterns available and it’s also used heavily in core Java libraries.
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern.
Java has several design patterns Singleton Pattern being the most commonly used.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it."
That means this design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
The key is not the problem and definition. In singleton pattern, tricky part is implementation and management of that single instance.
There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:

 1.Java.lang.Runtime with getRuntime() method
 2.Java.awt.Toolkit with getDefaultToolkit()
 3.Java.awt.Desktop with  getDesktop()

There are at least four ways to implement Singleton pattern in Java.
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums
This article is an attempt to explain the basics on singleton design pattern.If you want more insight on singleton then i will explain it in detail later.

No comments:

Post a Comment