1、饿汉模式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2、懒汉模式
public class Singleton {
private static Singletoninstance;
private Singleton() {}
public static synchronized SingletongetInstance() {
if(instance ==null) {
instance =new Singleton();
}
return instance;
}
}
3、双重检测
public 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;
}
4、静态内部类
public class Singleton {
private Singleton() {}
private static class SingletonHolder{
private static final Singletoninstance =new Singleton();
}
public static SingletongetInstance() {
return SingletonHolder.instance;
}
}
5、枚举类
public enum Singleton{
INSTANCE;
}