Ishan Soni Ishan Soni - 6 months ago 10
Java Question

Implementing Singleton using factory method

I am trying to create a class that has a singleton property using a static factory method..

package ishan.Beans;

public class ControlManager {

private static ControlManager controlManager=null;

private double id;

private ControlManager()
{
this.id=Math.random();
}

public static ControlManager getControlManager()
{

if(null==controlManager)
return new ControlManager();

return controlManager;
}

public double getId() {
return id;
}

}


package ishan.Beans;

public class Usage {

public static void main(String a[])
{
ControlManager cManager=ControlManager.getControlManager();

ControlManager c=ControlManager.getControlManager();

System.out.println(c);
System.out.println(cManager);
}

}


Every time I run this code, I get different instances of ControlManager in c and cManager. I am unable to figure out the problem or what is it that I am doing wrong.

Answer

You are not saving away the new instance you create... your code is:

public static ControlManager getControlManager()
{

    if(null==controlManager)
        return new ControlManager();

but should be:

public static ControlManager getControlManager() {

    if(controlManager == null) {
        controlManager = new ControlManager();
        return controlManager;
    }