Java中单例模式的几种实现
程序员文章站
2022-03-01 13:04:05
...
- 饿汉式单例
public class Single{
private static Single mInstance = new Single();
private Single(){}
public static Single getInstance(){
return mInstance;
}
}
优点是线程安全,缺点时没有办法实现懒加载。
- 懒汉式+同步方法单例
public class Single{
private static Signle mInstance;
private Single(){}
public static synchronized Single getInstance(){
if(mInstance == null){
mInstance = new Single();
}
return mInstance;
}
}
优点是线程安全,懒加载
缺点是效率不高
- volatile+Double Check方式
public class Single{
private volatile static Single mInstance;
private Single(){}
private static Single getInstance(){
if(mInstance == null){
synchronized(Single.class){
if(mInstance == null){
mInstance = new Single();
}
}
}
return mInstance;
}
}
优点是线程安全,效率还可以
- Holder模式
public class Single{
private Single(){}
private static class Holder{
private static Single instance = new Single();
}
public static Single getInstance(){
return Holder.instance;
}
}
优点是线程安全,懒加载,效率高。
- 枚举方式
public enum Single{
//单例变量,也是枚举变量
INSTANCE;
public static getInstance(){
return INSTANCE;
}
}
优点,线程安全
缺点,没有懒加载
- 枚举+Holder
public class Single{
private Single(){}
//这个枚举类型的Holder主要是为了确保单例
private enum EnumHolder{
INSTANCE;
//单例的枚举型中包含一个Single类型的变量
private Single instance;
EnumHolder(){
//在构造函数中延时初始化
this.instance = new Single();
}
//提供方法返回单例
private Single getInstance(){
return instance;
}
}
//通过枚举类型返回单例实例
public static Single getInstance(){
return EnumHolder.INSTANCE.getInstance();
}
}
上一篇: JAVA单例模式的几种实现方法
下一篇: JAVA单例模式的几种实现方法