package singletonDemo;
public class SingletonTest {
private static SingletonTest instance = null;
public SingletonTest() {
}
private static /*synchronized*/ void syncInit() {
if (instance == null) {
instance = new SingletonTest();
}
}
public static SingletonTest getInstance() {
if (instance == null) {
syncInit();
}
System.out.println("instance:"+instance);
return instance;
}
}
笔者做了很久的java开发一直没用过单例模式,学了忘记,忘记了再学。可能是自己不够用心吧。但是管理系统项目中很少用到单例模式,可能是工作流设计的时候,就没有单例模式设计工作流引擎。我们的项目特别大,当然也比较旧,没编译5G的大小,整个项目搜Singleton就是没搜到,估计就没用。
对着网友的帖子学习单例模式,发现几点跟作者不同的见解:
1、上面的代码中有synchronized关键字,我觉得没有必要,因为我测试,对象就只有一个,不管有没有synchronized关键字。
2、饿汉模式、懒汉模式、内部静态类模式对应的单例,其他网友已经写了不少了,笔者不再赘述。
总结:
private static /*synchronized*/ void syncInit() {}
这行代码的synchronized关键字,是不是有必要的?欢迎讨论赐教。