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

时间:2018-03-27 04:33:46

标签: 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 == 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();
    }
}

3 个答案:

答案 0 :(得分:4)

对于此用例,您只需将它们存储为默认值即可。如

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

话虽如此,您可能希望将默认构造函数更改为相同的方式。

答案 1 :(得分:2)

如果你可以创建XandY引用protected,你可以在匿名子类中使用静态初始化器:

// I need to reset the singleton!
new XandY(){
    { xy = null; }
};

但实际上,如果你需要能够(重新)初始化单例,你应该将一个方法放到它的签名中。晦涩难懂的解决方案充其量仍然模糊不清......

答案 2 :(得分:2)

创建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;
    }
}