1、定义
单例模式(Singleton Pattern)是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点。
隐藏其所有的构造方法。
属于创建型模式。
2、适用场景
确保任何情况下都绝对只有一个实例。
3、常见写法
第一种:饿汉式单例:在单例类首次加载时就创建实例
public class HungrySingleton {
private static final HungrySingleton INSTANCE = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return INSTANCE;
}
}
饿汉式单例静态代码块写法:
public class HungryStaticSingleton {
private static final HungryStaticSingleton INSTANCE;
static {
INSTANCE = new HungryStaticSingleton();
}
private HungryStaticSingleton() {
}
public static HungryStaticSingleton getInstance() {
return INSTANCE;
}
}
第二种:懒汉式单例:被外部类调用时才创建实例
public class LazySingleton {
private static LazySingleton INSTANCE = null;
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
懒汉式单例静态匿名内部类写法(性能最优):
public class LazyInnerClazzSingleton implements Serializable {
private LazyInnerClazzSingleton() {
}
public static final LazyInnerClazzSingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazyInnerClazzSingleton INSTANCE = new LazyInnerClazzSingleton();
}
}
第三种:注册式单例:将每一个实例都缓存到统一的容器中,使用唯一标识获取实例
注册式单例枚举写法:
public enum EnumSingleton {
INSTANCE;
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static EnumSingleton getInstance() {
return INSTANCE;
}
}
Spring中常见的注册式单例写法:
public class ContainerSingleton {
private static Map<String, Object> container = new ConcurrentHashMap<>();
private ContainerSingleton() {
}
public static Object getBean(String clazzName) {
// 加synchronized代码块保证线程安全
synchronized (container) {
if (!container.containsKey(clazzName)) {
Object object = null;
try {
object = Class.forName(clazzName).newInstance();
container.put(clazzName, object);
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
return container.get(clazzName);
}
}
}
第四种:ThreadLocal线程单例:保证线程内部的全局唯一,且天生线程安全
public class ThreadLocalSingleton {
public static final ThreadLocal<ThreadLocalSingleton> THREAD_LOCAL = new ThreadLocal<ThreadLocalSingleton>() {
@Override
protected ThreadLocalSingleton initialValue() {
return new ThreadLocalSingleton();
}
};
private ThreadLocalSingleton() {
}
public static ThreadLocalSingleton getInstance() {
return THREAD_LOCAL.get();
}
}
4、如何防止单例被破坏
1.多线程破坏单例以及解决方法
以懒汉式单例LazySingleton为例:
首先写一个线程实现类,如下:
import com.hzg.study.design.pattern.singleton.lazy.LazySingleton;
public class ExecutorThread implements Runnable {
@Override
public void run() {
LazySingleton instance = LazySingleton.getInstance();
System.out.println(Thread.currentThread().getName() + ":" + instance);
}
}
main方法测试:
public class LazySingletonTest {
public static void main(String[] args) {
Thread thread1 = new Thread(new ExecutorThread());
thread1.start();
Thread thread2 = new Thread(new ExecutorThread());
thread2.start();
System.out.println("----------------------------------------");
}
}
测试结果:显然出现了两个不同的实例
解决方法1:加synchronized关键字修饰getInstance方法
public class LazySingleton {
private static LazySingleton INSTANCE = null;
private LazySingleton() {
}
public static synchronized LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
解决方法2:双重检查锁DoubleCheck
public class LazyDoubleCheckSingleton {
private volatile static LazyDoubleCheckSingleton INSTANCE = null;
private LazyDoubleCheckSingleton() {
}
public static LazyDoubleCheckSingleton getInstance() {
if (INSTANCE == null) {
synchronized (LazyDoubleCheckSingleton.class) {
if (INSTANCE == null) {
INSTANCE = new LazyDoubleCheckSingleton();
}
}
}
return INSTANCE;
}
}
2.反射破坏单例以及解决方法
以懒汉式单例静态匿名内部类写法LazyInnerClazzSingleton为例:
main方法测试:
public class LazyInnerClazzSingletonTest {
public static void main(String[] args) {
try {
Class<LazyInnerClazzSingleton> aClazz = LazyInnerClazzSingleton.class;
Constructor<LazyInnerClazzSingleton> declaredConstructor = aClazz.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyInnerClazzSingleton instance1 = declaredConstructor.newInstance();
LazyInnerClazzSingleton instance2 = LazyInnerClazzSingleton.getInstance();
System.out.println(instance1);
System.out.println(instance2);
System.out.println(instance1 == instance2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试结果:构建了两个不同的实例
解决方法:在构造器中增加如下if判断
public class LazyInnerClazzSingleton implements Serializable {
private LazyInnerClazzSingleton() {
if (null != LazyHolder.INSTANCE) {
throw new RuntimeException("不允许构建多个实例");
}
}
public static final LazyInnerClazzSingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazyInnerClazzSingleton INSTANCE = new LazyInnerClazzSingleton();
}
}
再次测试:
3.序列化破坏单例以及解决方法
以懒汉式单例静态匿名内部类写法LazyInnerClazzSingleton为例:注意必须先实现序列化接口Serializable
main方法测试:
public static void main(String[] args) {
LazyInnerClazzSingleton instance1 = LazyInnerClazzSingleton.getInstance();
LazyInnerClazzSingleton instance2 = null;
try (
FileOutputStream fileOutputStream = new FileOutputStream("LazyInnerClazzSingleton.obj");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
FileInputStream fileInputStream = new FileInputStream("LazyInnerClazzSingleton.obj");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
) {
// 序列化
objectOutputStream.writeObject(instance1);
objectOutputStream.flush();
// 反序列化
instance2 = (LazyInnerClazzSingleton) objectInputStream.readObject();
System.out.println(instance1);
System.out.println(instance2);
System.out.println(instance1 == instance2);
} catch (Exception e) {
e.printStackTrace();
}
}
测试结果:构建了两个不同的实例
解决方法:新增readResolve方法
public class LazyInnerClazzSingleton implements Serializable {
private LazyInnerClazzSingleton() {
if (null != LazyHolder.INSTANCE) {
throw new RuntimeException("不允许构建多个实例");
}
}
public static final LazyInnerClazzSingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazyInnerClazzSingleton INSTANCE = new LazyInnerClazzSingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
5、优缺点
优点:
在内存中只有一个实例,减少了内存开销。
可以避免对资源的多重占用。
设置全局访问点,严格控制访问。
缺点:
没有接口,扩展困难。
如果要扩展单例对象,只有修改代码,没有其他途径。
不符合开闭原则
6、总结
1、私有化构造器
2、保证线程安全
3、延迟加载
4、防止序列化和反序列化破坏单例
5、防御反射攻击单例
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!