Better “SingleTon” handling

Singleton design pattern is a creational pattern, which restricts the instantiation of objects. The designers need to keep three things in their mind before setting a class to follow Singleton pattern. One: make the constructor invisible. Two:provide a static method that can create a new instance only if no instance is available. Three: override the public Object clone(). This one usually most of the people forget. Even I did it quite few times.

package subin.rnd.design.singleton;
public class SingletonObject
{
    private static SingletonObject _myInstance = null;
    
    private SingletonObject()
    {
       // actions to do while creating an object 
    }
    
    @Override
    public Object clone()
    {
        return (_myInstance);
    }
    
    public static SingletonObject getInstance()
    {
        if (_myInstance == null)
            _myInstance = new SingletonObject();
        return (_myInstance);
    }
    
    public void doSomething()
    {
        // do something
    }
}

Singleton test:

SingletonObject singletonObject = SingletonObject.getInstance();
SingletonObject newSingletonObject = (SingletonObject) singletonObject.clone();       
System.out.println("Equal ? " 
  + ((singletonObject == newSingletonObject) ? "yes" : "no"));
  
try
{
    newSingletonObject = (SingletonObject) Class.forName(
      "subin.rnd.design.singleton.SingletonObject").newInstance();
}
catch (InstantiationException e)
{
    e.printStackTrace();
}
catch (IllegalAccessException e)
{
    e.printStackTrace();
}
catch (ClassNotFoundException e)
{
    e.printStackTrace();
}

Output:

Equal ? yes
java.lang.IllegalAccessException: Class subin.rnd.design.singleton.SingletonTest 
 can not access a member of class subin.rnd.design.singleton.SingletonObject 
 with modifiers "private"
 at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
 at java.lang.Class.newInstance0(Unknown Source)
 at java.lang.Class.newInstance(Unknown Source)
 at subin.rnd.design.singleton.SingletonTest.main(SingletonTest.java:16)

Useful links:
http://en.wikipedia.org/wiki/Singleton_pattern

Advertisements