单例模式5种分类
1. 饿汉模式
2. 懒汉模式
3. 双重检查锁模式
4. 静态内部类模式
5. 枚举模式
模式具体实现
饿汉模式
public class SingletonDemo01 {
private static SingletonDemo01 instance = new SingletonDemo01();
private SingletonDemo01() {
}
public static SingletonDemo01 getInstance() {
return instance;
}
}
懒汉模式
public class SingletonDemo02 {
private static SingletonDemo02 instance;
private SingletonDemo02() {
}
public static synchronized SingletonDemo02 getInstance() {
if(instance == null) {
instance = new SingletonDemo02();
}
return instance;
}
}在这里插入代码片
双重检查锁模式
public class SingletonDemo05 {
private static SingletonDemo05 instance = null;
public static SingletonDemo05 getInstance() {
if(instance == null) {
SingletonDemo05 sc;
synchronized(SingletonDemo05.class) {
sc = instance;
if(sc == null) {
synchronized (SingletonDemo05.class) {
if(sc == null) {
sc = new SingletonDemo05();
}
}
instance = sc;
}
}
}
return instance;
}
private SingletonDemo05() {
}
}
静态内部类模式
public class SingletonDemo04 {
private static class Singleton{
private static final SingletonDemo04 getInstance = new SingletonDemo04();
}
private SingletonDemo04() {
}
public static SingletonDemo04 getInstance() {
return Singleton.getInstance;
}
}
枚举模式 ;
public enum SingletonDemo03 {
INSTANCE;
// 添加需要的操作
public void singletonOperation() {
}
}
防止反射和序列化
枚举模式天然可以防止反射和序列化 防止反射 在构造方法种抛出异常
private SingletonDemo6() {
// 防止反射
if(instance != null) {
throw new RuntimeException();
}
}
防止序列化 定义readResolve()方法
public Object readResolve() throws ObjectStreamException{
return instance;
}
单例模式选择
单例对象占用资源少,不需要延时加载时: 枚举好于饿汉式 单例对象占用资源大,需要延时加载时: 静态内部类好于懒汉式 双重检查锁模式(不建议使用),存在问题