gpt4 book ai didi

Java 单例方法允许对象有多个实例

转载 作者:行者123 更新时间:2023-12-01 21:59:29 25 4
gpt4 key购买 nike

我最初编写了以下代码。目的是确保在任何时间点仅创建一个类的一个对象。

public class singleinstance {
private static int instance;

public singleinstance(){
if(instance != 0){
throw new IllegalStateException("More than one instance");
}
System.out.println(instance);
instance ++;
System.out.println(instance);
}
}

后来,当我检查互联网以查看这是否是执行此操作的最佳方法时,我遇到了术语singleton,并使用私有(private)构造函数,并遇到了 This link我在其接受的答案部分尝试了相同的代码,但是通过定义一个计数器变量并打印它,并且可以看到类实例的数量不止一个。我粘贴下面的代码。

public class Singleton {
private static int counter=0;
private static Singleton instance;

/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}

/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}

/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}

// other methods protected by singleton-ness would be here...
/** A simple demo method */
public int demoMethod() {
counter++;
return counter;
}
}

单例测试.java

public class Singletontest {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
System.out.println(tmp.demoMethod());
Singleton tmp1 = Singleton.getInstance();
System.out.println(tmp1.demoMethod());
}
}

测试类在执行时打印12,这意味着使用单例类创建了该类的两个实例。如果这是可能的,为什么它被认为是单例?请澄清我的理解。

编辑:: 对该方法的调用再次增加了该值。但同样,我可以多次交替调用方法 tmp1.demoMethod()、tmp.demoMethod(),这让我认为 tmp 和 tmp1 是创建的两个对象。我如何确认,或者我可以调查哪些内容,以确认这只是一个实例?

最佳答案

在您的示例中,tmp 和 tmp1 是同一对象实例。您可以通过打印两个对象来检查它:

System.out.println(tmp);
System.out.println(tmp1);

之后,您对同一对象调用该方法两次,并且计数器递增两次。但只创建了一个Singleton对象

关于Java 单例方法允许对象有多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33803396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com