单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
单例类只能有一个实例。单例类必须自己创建自己的唯一实例。单例类必须给所有其他对象提供这一实例。懒汉式
public class Singleton implements Serializable { private volatile static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } }这种方式是懒汉式最基本的实现方式,这种实现最大的问题就是不支持多线程。因为没有加锁 synchronized,所以严格意义上它并不算单例模式。 这种方式 lazy loading 很明显,不要求线程安全,在多线程不能正常工作。
饿汉式
public class Singleton implements Serializable { private static final Singleton SINGLETON = new Singleton(); private Singleton() {} public static Singleton getInstance() { return SINGLETON; } }饿汉式基于 classloader 机制避免了多线程的同步问题,不过,instance 在类装载时就实例化,虽然导致类装载的原因有很多种,在单例模式中大多数都是调用 getInstance() 方法, 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化 instance 显然没有达到 lazy loading 的效果。
综上所述,我们可以看出使用懒汉式的方式创建的单例模式在多线程下并不是安全的,所以提出了使用双重校验锁的方式来实现懒汉式的单例
双重校验锁实现懒汉式
public class Singleton implements Serializable { private volatile static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { // 加了类锁,保证了线程安全 synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }这种方式采用双锁机制,安全且在多线程情况下能保持高性能。
但是我们想想,这样做完真的就可以保证程序中有且仅有一个单例对象的存在了吗?答案是否定的,我们可以通过反射的方式来破坏单例
使用反射破坏单例
// 使用反射来破坏单例模式 public static void main(String[] args) throws Exception { // 获取普通单例对象 Singleton instance = Singleton.getInstance(); Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor(); // 破解 private constructor.setAccessible(true); // 执行构造方法创建对象 Singleton singleton = constructor.newInstance(); System.out.println(singleton); // Singleton@4554617c System.out.println(instance); // Singleton@74a14482 System.out.println(singleton == instance); // false }我们使用反射获取了 Singleton 的无参构造器,通过调用 setAccessible(true) 忽视 private 权限控制符,成功的创建了 Singleton 的对象。反射创建对象的根本方法就是获取了 Singleton 的私有构造器,那么针对的方法也就很简单了,只需要我们在私有构造器中再次判断单例对象是否已经创建,若存在已创建的单例对象,则抛出运行时异常即可!
解决使用反射破坏单例
public class Singleton implements Serializable { private volatile static Singleton singleton; private Singleton() { // 防止反射调用无参构造器破坏单例模式 if (singleton != null) { throw new RuntimeException("不能重复创建该对象"); } } public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }使用反射再次创建对象后运行截图如下:
我们现在已经防止了多线程下和使用反射来破坏单例了。现在我们的单例模式是不是真的就安全了呢?其实除了反射以外,使用 序列化与反序列化也同样可以破坏单例!
使用序列化反序列化破坏单例
public static void main(String[] args) throws Exception { Singleton instance = Singleton.getInstance(); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("tempfile")); os.writeObject(instance); ObjectInputStream is = new ObjectInputStream(new FileInputStream("tempfile")); Singleton singleton = (Singleton) is.readObject(); System.out.println(singleton); // Singleton@4dd8dc3 System.out.println(instance); // Singleton@7f31245a System.out.println(singleton == instance); // false }可以看出单例模式又再次被破坏了。为了解决序列化和反序列化破坏单例模式的问题,我们可以定义一种称为 readResolve() 的特殊序列化方法。如果我们定义了 readResolve() 方法,那么在对象被序列化后就会被调用。
修改 Singleton 类并增加 addResolve() 方法
public class Singleton implements Serializable { private volatile static Singleton singleton; private Singleton() { // 防止反射调用无参构造器破坏单例模式 if (singleton != null) { throw new RuntimeException("不能重复创建该对象"); } } public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } /** * 防止被序列化破坏单例模式 * @return */ private Object readResolve() { return singleton; } }再次运行序列化和反序列化程序,可以观察到如下的结果
不过我们还有一种最简单的方式去创建一个单例模式,那就是使用 枚举 来创建单例模式
使用枚举创建单例模式
enum SingletonEnum { /** * 实例 */ INSTANCE; private Singleton singleton = null; SingletonEnum() { singleton = new Singleton(); } public Singleton getInstance() { return singleton; } }运行类 及 结果
public class Singleton { public static void main(String[] args) { Singleton instance = SingletonEnum.INSTANCE.getInstance(); Singleton singleton = SingletonEnum.INSTANCE.getInstance(); System.out.println(instance == singleton); //true } }