请教关于java的单态模式

来源:百度知道 编辑:UC知道 时间:2024/06/27 10:00:26
我写了一个标准的单态模式的类.结构如下:
public class Test{
private static Test instance = null;
public static synchronized Test getInstance() {
if(instance==null){
System.out.println("here run init()");
instance = new Test();
}
return instance;
}

private Test() {
init();
}

private init(){
Properties p = new Properties();
try{
properties.load(Test.class.getResourceAsStream("/option.properties"));
//以下是取配置,设置初始化配置的代码,此处略掉
}catch(Exception ioEx){
System.out.println("配置文件option.properties不存在");
}
}
}

在运行时我发现: System.out.println("here run init()");这句运行了两次. 我想请教这是什么原因,如何解决!

说明几点:
1.问题肯定是出在我贴出来的代码中,因为我把其它代码全注掉,只留这段都仍然有这个问题,所以不要怀疑是其它的代码有问题. 而且,只要我注掉 properties.load(...)这一句,初始化就只执行一次了,我想就是这句的问题.
2.从结果上来看,这个类的初始化代码被执行了两次,我想知道的,就是为什么会这样和么解决它, 目的是只让这个初始化函数执行一次.
3.谢谢绝复制

从你的代码来看只有调用getInstance()方法,才会运行System.out.println("here run init()"); 这一句吧。
就算是在properties.load(...)这一句时构造函数又加载了一次,也不会输出"here run init()"这一句啊~
晕了~
=========================================================
我编译了下你这段代码(稍微有点修改)
import java.util.*;

public class Test{
private static Test instance = null;
public static synchronized Test getInstance() {
if(instance==null){
System.out.println("here run init()");
instance = new Test();
}
return instance;
}

private Test() {
init();
}

private void init(){
Properties p = new Properties();
try{
p.load(Test.class.getResourceAsStream("/option.properties"));
//以下是取配置,设置初始化配置的代码,此处略掉
}catch(Exception ioEx){
System.out.println("配置文件option.properties不存在");
}
}

public static void main(String[] args){