T.H.
T.H.

Reputation: 89

How to make a singleton reinitialize variables?

My singleton class:

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

Other class that changes singleton values and tries to reinitialize. My question is if I call changeXandY a few times then want to call resetXandY how do I make it reset back to the original x and 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();
    }
}

Upvotes: 2

Views: 1732

Answers (3)

Nitin Sharma
Nitin Sharma

Reputation: 100

Create a resetXandY() method to set default value:

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

Upvotes: 2

Bob Jacobsen
Bob Jacobsen

Reputation: 1160

If you can make the XandY reference protected, you can use a static initializer in an anonymous subclass:

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

But really, if you need to be able to (re)initialize the singleton, you should put a method to that effect into its signature. Obscure solutions are, at best, still obscure...

Upvotes: 2

Haris Nadeem
Haris Nadeem

Reputation: 1334

For this use case, you could simply store them as default values. Such as

    private double x, y;
    private static XandY xy;
    private static final double default_x = 210.0;
    private static final double default_y = 100.0;

That way when you reset, just:

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

That being said, you may want to change your default constructor to look the same way.

Upvotes: 5

Related Questions