单例模式模板
作者:
Happy丶
,
2024-09-24 11:33:12
,
所有人可见
,
阅读 3
饿汉式:静态成员变量
public class Singleton{
private Singleton(){};
private static Singleton instanse = mew Singleton();
public static Singleton getInstance(){
return instance;
}
}
饿汉式,静态代码块
public class Singleton{
private Singleton(){};
private static Singleton instance;
static{
instance = new Singleton();
}
public static Singleton getInstance(){
return instance;
}
}
饿汉式,枚举
public enum Singleton{
INSTANCE;
}
懒汉式:线程不安全
public class Singleton{
private Singleton(){};
private static Singleton instance;
private static Singleton getInstance(){
if(instance == null){
return new Singleton();
}
return instance;
}
}
懒汉式:线程安全
public class Singleton{
private Singleton(){};
private static Singleton instance;
private static synchronized Singleton getInstance(){
if(instance == null){
return new Singleton();
}
return instance;
}
}
懒汉式:双重检查锁
public class Singleton{
private Singleton(){};
private static volatile Singleton instance;
private static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
懒汉式:静态内部类
public class Singleton{
private Singleton(){};
public static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}