Saturday, 9 March 2013

Singleton Design Pattern

Hi Friends....!!
Hi Friends....!!!                             





I would like to share some of my views about Singleton Design Pattern.


For any java class if we are allowed to create any one object, such type of class is called as ‘Singleton class’.

Example:
Runtime, ActionServlet(Struts 1.x), BussinessDeligate(EJB), ServiceLocation(EJB),…., etc.

Singleton Design pattern is mainly used to restrict the creation of instances of a class to one. This is the most common and easiest design pattern in java.

For a Singleton class,
  • There should be only one instance allowed for a class
  • That single instance should able allow global point of access

The Only Child.... :p


Example for Singleton class:

We can create our own Singleton class by providing

public class Singleton{
    private static Singleton objSingleton;
    private Singleton(){
    }
    
    // Factory Method
    public  static Singleton getInstance(){
        if(objSingleton == null)
            objSingleton = new Singleton();
        return objSingleton;
    }
    // override clone method
    public  Object clone(){
        return this;
    }
}

To be Noted In Above Singleton Class :
  • Constructor of the class is made private to restrict the direct instantiation of the object.
  • Factory method is created to get an instance of an object
  • Clone method is overridden to restrict creation of copies of the object.




Preventing Singleton Class from Multi-Threading Problems:

If you needed to prevent this Singleton from multi threading problems, it is advisable to mark the factory method as synchronized.
The snippet is provide below:
public static synchronized Singleton getInstance(){
    if(objSingleton == null)
        objSingleton = new Singleton();
    return objSingleton;
}





Usage of Singleton Class:

Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
Singleton obj3 = Singleton.getInstance();
Singleton obj4 = Singleton.getInstance();

It actually creates as below:












All the instances of Singleton are same, but having multiple references.

3 comments:

  1. Very Interesting n important post buddy :p

    ReplyDelete
  2. Very useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
    kindle mobi formatting services

    ReplyDelete