/**
* 单例模式 - 饿汉式
*
* 类加载时初始化实例,线程安全;对象较大且一直不使用会浪费内存
*/
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
/**
* 单例模式 - 懒汉式
*/
public class Singleton {
// volatile 线程间可见,防止指令重排序对new对象时的影响
private static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
// double check lock
if (null == instance) {
synchronized (Singleton.class) {
if (null == instance) {
/*
* 1.分配内存空间
* 2.初始化对象
* 3.将instance指向分配好的内存空间
* */
instance = new Singleton();
}
}
}
return instance;
}
}
/**
* 单例模式-静态内部类
*
* 延时加载,线程安全
*/
public class Singleton {
private Singleton() {
// 防止反射时访问私有构造方法
if (SingletonHandler.instance != null) {
throw new RuntimeException("不支持反射访问");
}
}
public static Singleton getInstance() {
return SingletonHandler.instance;
}
public static class SingletonHandler {
// 静态内部类在第一次使用时才会加载
private static Singleton instance = new Singleton();
}
}
/**
* 单例模式-枚举
*
* 阻止反射的破坏: 在反射方法中不允许使用反射创建枚举对象
* 阻止序列化的破坏: 在序列化的时候仅仅是将枚举对象的name属性输出到了结果中,反序列化的时候,就会通过Enum的 valueOf方法 来根据名字去查找对应枚举对象.
*/
public enum Singleton {
INSTANCE;
public static Singleton getInstance() {
return INSTANCE;
}
}