You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让单例类XandY重新初始化变量,恢复初始值?

How to Add a resetXandY Method to the XandY Singleton Class

Hey there! Adding reset functionality to your singleton is straightforward—here are two solid approaches to get it done, depending on how maintainable you want the code to be:

Approach 1: Direct Reset (Simple but Less Maintainable)

If you don’t anticipate changing the initial x/y values often, you can hardcode the reset values directly in a new method:

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

    // New reset method to restore initial values
    public void resetXandY() {
        x = 210.0;
        y = 100.0;
    }
}

This works perfectly for one-off cases, but if you ever need to change the initial coordinates later, you’ll have to update both the constructor and the resetXandY method—easy to miss!

Approach 2: Use Constants (More Maintainable)

A better practice is to define your initial values as static final constants. This way, you only need to update them in one place if they ever change:

public class XandY { 
    // Store initial values as constants for easy updates
    private static final double INITIAL_X = 210.0;
    private static final double INITIAL_Y = 100.0;

    private double x, y; 
    private static XandY xy; 

    // Constructor uses constants instead of hardcoded values
    private XandY() { 
        x = INITIAL_X; 
        y = INITIAL_Y; 
    } 

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

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

    // Reset method leverages the same constants
    public void resetXandY() {
        x = INITIAL_X;
        y = INITIAL_Y;
    }
}

Now, whenever you need to adjust the starting position, just modify the INITIAL_X and INITIAL_Y constants, and both the constructor and reset method will automatically use the new values.

Quick Side Note

If this singleton will be used in a multi-threaded environment, the current getXandY() method isn’t thread-safe. You might want to implement double-checked locking or use an enum-based singleton pattern to fix that, but that’s a separate topic from your reset requirement!

内容的提问来源于stack exchange,提问作者T.H.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:15:19