单例模式的五种写法(Java)

最后一次更新时间:Friday, January 22nd 2021, PM

 

饿汉式

1
2
3
4
5
6
7
public class Singleton{
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}

 

 

 

懒汉式(线程不安全)

1
2
3
4
5
6
7
8
9
10
11
public class Singleton{
private static Singleton instace;
private Singleton(){}

public static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instace;
}
}

 

 

 

懒汉式(线程安全)

效率低,每次都要加锁

1
2
3
4
5
6
7
8
9
10
11
public class Singleton{
private static Singleton instace;
private Singleton(){}

public static synchronized Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instace;
}
}

 

 

 

双重校验锁 DCL(Double Checked Locking)

先判断,若对象已创建,则不进入synchronized代码块。提升了性能且保证安全。
Volate一般用于保证多线程可见性。这里用来防止指令重排序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton{
private volatile static Singleton instance;
private Singleton(){};
public static Singleton getInstance(){
if (instance == null){
synchronized(Singleton.class){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}

 

 

 

静态内部类

调用getInstance()才初始化,更加灵活

1
2
3
4
5
6
7
8
9
public class Singleton{
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
private Singleton(){}
public static final Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}

除特别声明外,本站所有文章均采用 CC BY-SA 4.0 协议 ,转载请注明出处!