线程安全单例设计模式

线程安全的单例设计模式有多种,如下推荐使用Holder方式。
(1)饿汉式
特点:getInstance 性能高,非懒加载。
public final class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){
//初始化
}
public static Singleton getInstance(){
return instance;
}
}
(2)枚举式
特点:getInstance 性能高,非懒加载
public enum Singleton {
INSTANCE;
private Singleton(){
//初始化
}
public static Singleton getInstance(){
return INSTANCE;
}
}
(3)懒汉式
特点:getInstance 性能低(需要同步),懒加载。
public final class Singleton {
private static Singleton instance;
private Singleton(){
//初始化
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
(4)Double-Check
特点:getInstance 性能高,懒加载。
public final class Singleton {
private static volatile Singleton instance;
private Singleton(){
//初始化
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
(5)Holder方式(推荐)
特点:getInstance 性能高,懒加载。
public final class Singleton {
private Singleton(){
//初始化
}
private static class Holder{
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return Holder.instance;
}
}
(6)枚举Holder方式
public final class Singleton {
private Singleton(){
//初始化
}
private enum Holder {
INSTANCE;
private Singleton instance;
private Holder() {
instance = new Singleton();
}
}
public static Singleton getInstance() {
return Holder.INSTANCE.instance;
}
}

Add a Comment

电子邮件地址不会被公开。 必填项已用*标注