懒汉式(能实现延迟加载,线程不安全)
public class LazySingleton{
private static LazySingleton instance;
private LazySingleton(){
}
public static LazySingleton getInstance(){
if(instance == null){
instance = new LazySingleton();
}
return instance;
}
}
饿汉式(不能实现延迟加载,天然线程安全)
instance是静态变量,在类初始化的时候便立即加载,因此天然是线程安全的。
getInstance方法没有加同步锁,因此调用效率更高
public class Singleton{
private static Singleton instance = new Singleton();
private Singleton(){
}
public static getInstance(){
return instance;
}
}
静态内部类(线程安全,调用效率高,实现了延迟加载)
public class StaticInnerClass{
private Static{
}
private static class StaticInnerClassInstance(){
private static final StaticInnerClass INSTANCE = new StaticInnerClass();
}
public static StaticInnerClass getInstance(){
return StaticInnerClass.INSTANCE;
}
}
双重检查锁(不推荐使用)
public class DoubleCheck{
private static DoubleCheck instance = new DoubleCheck();
private DoubleCheck(){
}
public static DoubleCheck getInstance() {
if (instance == null) {
DoubleCheck dc;
synchronized (DoubleCheck.class) {
dc = instance;
if (dc == null) {
synchronized (DoubleCheck.class) {
if (dc == null) {
dc = new DoubleCheck();
}
}
instance = dc;
}
}
}
return instance;
}
}
懒汉式(防止单例、序列化)
public LazySingleton implements Serializable{
private static volatile LazySingleton instance;
private LazySingleton(){
if(instance != null){
throw new RuntimeException();
}
}
public synchronzied LazySingleton getInstance(){
if(instance == null){
instance = new LazySingleton();
}
return instance;
}
/**
* 反序列化时,如果定义了readResolve方法则直接返回此方法指定的对象,而不需要再单独创建对象
*/
public Object ReadResolve() throws ObjectStreamException{
return instance;
}
}
枚举(枚举元素本身就是单例对象)
public enum EnumSingleton(){
INSTANCE;
public void singletonOperation(){
}
}