我正在尝试使用静态工厂方法创建具有单例属性的类。

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

}

每次运行此代码时,我在c和cManager中都会得到ControlManager的不同实例。我无法弄清楚问题或我做错了什么。

最佳答案

您并没有保存创建的新实例...您的代码是:

public static ControlManager getControlManager()
{

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

但应为:
public static ControlManager getControlManager() {

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

关于java - 使用工厂方法实现Singleton,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26140874/

10-12 03:41