1、单机版下的单列模式
public class SingletonDemo {
private static SingletonDemo singletonDemo;
private SingletonDemo(){
}
public static SingletonDemo getInstance(){
if (singletonDemo==null){
singletonDemo = new SingletonDemo();
}
return singletonDemo;
}
}
2、多线程下的单列模式--DCL双端检索机制(潜在问题,指令会重排)
public class SingletonDemo {
private static SingletonDemo singletonDemo;
private SingletonDemo() {
}
public static SingletonDemo getInstance() {
if (singletonDemo == null) {
synchronized (SingletonDemo.class) {
if (singletonDemo == null) {
singletonDemo = new SingletonDemo();
}
}
}
return singletonDemo;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/c6f4fef3bb85360c63a31d38a969a0cc.png)
![](https://i-blog.csdnimg.cn/blog_migrate/68dd6cc4d9a719e11e57b560dff3ee1d.png)
3、多线程下的单列模式--DCL+volatile
public class SingletonDemo {
private static volatile SingletonDemo singletonDemo;
private SingletonDemo() {
}
public static SingletonDemo getInstance() {
if (singletonDemo == null) {
synchronized (SingletonDemo.class) {
if (singletonDemo == null) {
singletonDemo = new SingletonDemo();
}
}
}
return singletonDemo;
}
}