Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使单例重新初始化变量?_Java - Fatal编程技术网

Java 如何使单例重新初始化变量?

Java 如何使单例重新初始化变量?,java,Java,我的单身班: public class XandY { private double x, y; private static XandY xy; //Constructor sets an x and y location private XandY() { x = 210.0; y = 100.0; } public static XandY getXandY() { if (xy == nu

我的单身班:

public class XandY {
    private double x, y;
    private static XandY xy;

    //Constructor sets an x and y location
    private XandY() {
        x = 210.0;
        y = 100.0;
    }

    public static XandY getXandY() {
        if (xy == null)
            xy = new XandY();
        return xy;
    }

    public void updateXandY() {
        x += 10;
        y += 5;
    }
}
更改单例值并尝试重新初始化的其他类。我的问题是,如果我多次调用changeXandY,然后想调用resetXandY,那么如何将其重置回原始的x和y

public class GameWorld {
    private List<GameObject> objects;

    public void initialize() {
        objects = new ArrayList<GameObject>();
        objects.add(XandY.getXandY());
        ...add other objects that are not singletons
    }

    public void changeXandY {
        for (int i=0; i<gameObject.size(); i++) {
        if (gameObject.get(i) instanceof XandY)
        ((XandY)gameObject.get(i)).updateXandY();
    }

    public void resetXandY {
        initialize();
    }
}
公共类游戏世界{
私有列表对象;
公共无效初始化(){
objects=newarraylist();
add(XandY.getXandY());
…添加其他非单例对象
}
公共空间变化{

对于(inti=0;i对于这个用例,您可以简单地将它们存储为默认值

    private double x, y;
    private static XandY xy;
    private static final double default_x = 210.0;
    private static final double default_y = 100.0;
这样,当您重置时,只需:

    public void resetXandY {
        this.x = default_x;
        this.y = default_y;
    }

也就是说,您可能希望更改默认构造函数,使其外观相同。

如果您可以使XandY引用受保护
,则可以在匿名子类中使用静态初始值设定项:

// I need to reset the singleton!
new XandY(){
    { xy = null; }
};
但实际上,如果您需要能够(重新)初始化singleton,您应该在其签名中加入这样的方法。模糊的解决方案充其量仍然是模糊的…

创建一个
resetXandY()
方法来设置默认值:

public class XandY {
    private double x, y;
    private static XandY xy;

    //Constructor sets an x and y location
    private XandY() {
        x = 210.0;
        y = 100.0;
    }

    //reset x=0 and y=0
    public void resetXandY() {
        x = 0;
        y = 0;
    }

    public static XandY getXandY() {
        if (xy == null)
            xy = new XandY();
        return xy;
    }

    public void updateXandY() {
        x += 10;
        y += 5;
    }
}

这在singleton类中是可能的?-->new XandY()@RanjithKumar您必须具有
受保护的
访问权限,因此您必须修改XandY类,但是是的,这是可能的。