Java 为什么单例类会生成多个对象?
我从一个教程中选取了这个例子。创建下面给定的类是为了限制在同一类中创建多个对象。 但当我试图在同一个包中的另一个类中从同一个类创建多个对象时,我成功了。 为什么会发生这种情况,或者我不理解创建多个对象的过程???Java 为什么单例类会生成多个对象?,java,singleton,Java,Singleton,我从一个教程中选取了这个例子。创建下面给定的类是为了限制在同一类中创建多个对象。 但当我试图在同一个包中的另一个类中从同一个类创建多个对象时,我成功了。 为什么会发生这种情况,或者我不理解创建多个对象的过程??? 请帮忙 对Test1createObject的第二次和第三次调用实际上并没有创建singleton类的另一个实例q.v。构造函数的代码: public static Test1 createObject() { // create a single instance the
请帮忙 对Test1createObject的第二次和第三次调用实际上并没有创建singleton类的另一个实例q.v。构造函数的代码:
public static Test1 createObject() {
// create a single instance the first time around
if (tstObj == null) {
tstObj = new Test1();
}
// otherwise return the instance which already exists
return tstObj;
}
请仔细注意,如果引用为null,if语句只会实例化singleton,理想情况下,这只会在应用程序第一次调用createObject时发生。请阅读createObject的代码。第二次调用时会发生什么?在第二次和后续通话中,tstObj的价值是多少?归还什么?
package interview;
public class Test {
public static void main(String[] args) {
Test1 myobject = Test1.createObject();
myobject.display();
Test1 myobject1 = Test1.createObject();
myobject1.display();
Test1 myobject2 = Test1.createObject();
myobject2.display();
}
}
public static Test1 createObject() {
// create a single instance the first time around
if (tstObj == null) {
tstObj = new Test1();
}
// otherwise return the instance which already exists
return tstObj;
}