前言

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

单例设计模式分类两种:
饿汉式:类加载就会导致该单实例对象被创建
懒汉式:类加载不会导致该单实例对象被创建,而是首次使用该对象时才会创建


一、实现方式

1、饿汉式(静态变量)

//饿汉式(静态常量)
public class Singleton1 {
    //构造器私有化,外部不能new
    private Singleton1() {}
    //本类创建对象实例
    private final static Singleton1 instance = new Singleton1();
    //提供一个公有的静态方法,返回对象实例
    public static Singleton1 getInstance() {
        return instance;
    }
}
  1. 优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
  2. 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费

2、饿汉式(静态代码块)

//饿汉式(静态代码块)
public class Singleton2 {
    //构造器私有化,外部不能new
    private Singleton2() {}
    //本类创建对象实例
    private static Singleton2 instance;
    static {
        instance = new Singleton2();
    }
    //提供一个公有的静态方法,返回对象实例
    public static Singleton2 getInstance() {
        return instance;
    }
}

这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例。优缺点和上面是一样的。

3、懒汉式(线程不安全)

//懒汉式(线程不安全)
public class Singleton3 {
    private static Singleton3 instance;
    private Singleton3() {}
    //提供一个静态的公有方法,当使用到该方法时,才去创建instance 即懒汉式
    public static Singleton3 getInstance() {
        if (instance == null){
            instance = new Singleton3();
        }
        return instance;
    }
}
  1. 起到了Lazy Loading的效果,但是只能在单线程下使用。
  2. 如果在多线程下,一个线程进入了if (instance == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式。

4、懒汉式(线程安全,同步方法)

//懒汉式(线程安全)
public class Singleton4 {
    private static Singleton4 instance;
    private Singleton4() {}
    //提供一个静态的公有方法,当使用到该方法时,才去创建instance 即懒汉式
    public static synchronized Singleton4 getInstance() {
        if (instance == null){
            instance = new Singleton4();
        }
        return instance;
    }
}
  1. 解决了线程不安全问题
  2. 效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接return就行了。方法进行同步效率太低

5、懒汉式(线程安全, 同步代码块)

//懒汉式(线程安全, 同步代码块)
public class Singleton5 {
    private static Singleton5 instance;
    private Singleton5(){};
    //提供一个静态的公有方法,当使用到该方法时,才去创建instance 即懒汉式
    public static Singleton5 getInstance() {
        if (instance == null){
            synchronized(Singleton5.class){
                instance = new Singleton5();
            }
        }
        return instance;
    }
}
  1. 这种方式,本意是想对第四种实现方式的改进,因为前面同步方法效率太低,改为同步产生实例化的的代码块
  2. 但是这种同步并不能起到线程同步的作用。跟第3种实现方式遇到的情形一致,假如一个线程进入了if (instance == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例

6、懒汉式(双重检查)

//双重检查
public class Singleton6 {
    private Singleton6() {}
    private static volatile Singleton6 instance;
    public static Singleton6 getInstance() {
        //第一次判断,如果instance不为null,不进入抢锁阶段,直接返回实际
        if (instance == null){
            synchronized(Singleton5.class){
                //抢到锁之后再次判断是否为空
                if (instance == null){
                    instance = new Singleton6();
                }
            }
        }
        return instance;
    }
}
  1. Double-Check概念是多线程开发中常使用到的,如代码中所示,我们进行了两次if (instance == null)检查,这样就可以保证线程安全了。
  2. 这样实例化代码只用执行一次,后面再次访问时,判断if (instance == null),直接return实例化对象,也避免的反复进行方法同步
  3. 添加 volatile 关键字之后可以很好解决双重检查锁模式带来空指针异常的问题,能够保证在多线程的情况下线程安全也不会有性能问题
  4. 线程安全;延迟加载;效率较高。在实际开发中,推荐使用这种单例设计模式

7、懒汉式(静态内部类)

//静态内部类
public class Singleton7 {
    private Singleton7() {}
    //提供一个静态的公有方法,当使用到该方法时,才去创建instance 即懒汉式
    private static class SingletonInstance {
        private static final Singleton7 INSTANCE = new Singleton7();
    }
    public static Singleton7 getInstance() {
        return SingletonInstance.INSTANCE;
    }
}
  1. 这种方式采用了类装载的机制来保证初始化实例时只有一个线程。
  2. 静态内部类方式在Singleton类被装载时并不会立即实例化,而是在需要实例化时,调用getInstance方法,才会装载SingletonInstance类,从而完成Singleton的实例化。
  3. 类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。
  4. 优点:避免了线程不安全,利用静态内部类特点实现延迟加载,效率高

8、饿汉式(枚举)

//枚举
public enum Singleton8 {
    INSTANCE
}

枚举类实现单例模式是极力推荐的单例实现模式,因为枚举类型是线程安全的,并且只会装载一次,设计者充分的利用了枚举的这个特性来实现单例模式,枚举的写法非常简单,而且枚举类型是所用单例实现中唯一一种不会被破坏的单例实现模式。


二、存在问题

上述写法,除了枚举以外都是可以通过序列化和反射来实现创建多个对象,从而破坏单例模式。

1、序列化和反序列化

单例类:

public class Singleton implements Serializable {
    private Singleton() {}
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static synchronized Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

序列化方法:

//从文件中读数据
public static Singleton readObjectFromFile() throws IOException, ClassNotFoundException {
    //创建对象输入流对象
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.txt"));
    //读取Singleton对象
    return (Singleton) ois.readObject();
}

//向文件中读数据
public static void writeObjectToFile() throws IOException {
    //创建对象输出流
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.txt"));
    //将instance对象写出到文件中
    oos.writeObject(Singleton.getInstance());
    oos.close();
}

测试:

public class Demo3 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        writeObjectToFile();
        Singleton singleton1 = readObjectFromFile();
        Singleton singleton2 = readObjectFromFile();

        System.out.println("singleton1: " + singleton1.hashCode());
        System.out.println("singleton2: " + singleton2.hashCode());
        System.out.println(singleton1 == singleton2);
    }
}

在这里插入图片描述

解决

在Singleton类中添加readResolve()方法,在反序列化时被反射调用,如果定义了这个方法,就返回这个方法的值,如果没有定义,则返回新new出来的对象。

public class Singleton implements Serializable {
    private Singleton() {}
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static synchronized Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
    /**
     * 下面是为了解决序列化反序列化破解单例模式
     * 当进行反序列化时,会自动调用该方法,将该方法的返回值直接返回
     */
    private Object readResolve() {
        return SingletonInstance.INSTANCE;
    }
}

效果图:在这里插入图片描述
反序列化原码分析:
在这里插入图片描述

2、反射

单例类:

public class Singleton {
    private Singleton() {
        
    }
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static synchronized Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

测试类:

public class Demo4 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class aClass = Singleton.class;
        Constructor cons = aClass.getDeclaredConstructor();
        cons.setAccessible(true);
        Singleton singleton1 = (Singleton) cons.newInstance();
        System.out.println("singleton1: " + singleton1.hashCode());
        Singleton singleton2 = (Singleton) cons.newInstance();
        System.out.println("singleton2: " + singleton2.hashCode());
        System.out.println(singleton1 == singleton2);
    }
}

在这里插入图片描述

解决

单例类:

class Singleton {
    private static boolean flag = false;
    private Singleton() {
        if (flag){
            throw new RuntimeException("不能创建多个对象");
        }
        flag = true;
    }
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static synchronized Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

在这里插入图片描述

这种方式比较好理解,直接杜绝反射创建单例模式。


三、拓展

在日常开发中,多线程,高并发的环境下,非工具类的单例对象常常会遇到多线程并发安全问题,例如说全局使用一个内存缓存的情况,无法高效的避免一个读,一个写的问题,很容易产生脏读幻读,甚至死锁的问题。

问了避免这类问题,在条件允许的情况下,还可以使用伪单例的方式(一个线程一个单例)。以alibaba的guava缓存为例:

添加依赖:

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2.2</version>
</dependency>

枚举单例类:

public enum CacheGenerator {
    generator;
    //存储缓存对象,一个线程对应一个缓存对象
    private final static Map<Thread, CacheTest> map = new ConcurrentHashMap<>();
    public CacheTest instance(){
        Thread thread = Thread.currentThread();
        //第一次创建,后续直接Map获取,保证程序运行时一个线程只有一个缓存对象
        if (!map.containsKey(thread)){
            map.put(thread, new CacheTest());
        }
        return map.get(thread);
    }
}

缓存类:

public class CacheTest {
    private final Cache<String, String> cache;
    public CacheTest(){
        cache = CacheBuilder
                .newBuilder()
                .concurrencyLevel(1)
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .initialCapacity(30000)
                .maximumSize(30000)
                .build();
    }
    public synchronized String get(String key){
        return cache.getIfPresent(key);
    }
    public synchronized void put(String key, String value){
        cache.put(key, value);
    }
}

测试类:

public class Demo1_2 {
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            Thread.currentThread().setName("Thread1");
            String name = Thread.currentThread().getName();
            CacheTest cache = CacheGenerator.generator.instance();
            System.out.println(name + " -> 缓存对象: " + cache.hashCode());
            cache.put("1", "zs");
            System.out.println(name + " -> get(1): " + cache.get("1"));//zs
            System.out.println(name + " -> get(2): " + cache.get("2"));//线程内是单例,线程之间隔离,返回 null
        }).start();
        new Thread(() -> {
            Thread.currentThread().setName("Thread2");
            String name = Thread.currentThread().getName();
            CacheTest cache = CacheGenerator.generator.instance();
            System.out.println(name + " -> 缓存对象: " + cache.hashCode());
            cache.put("2", "ls");
            System.out.println(name + " -> get(1): " + cache.get("1"));//线程内是单例,线程之间隔离,返回 null
            System.out.println(name + " -> get(2): " + cache.get("2"));//ls
        }).start();
    }
}

在这里插入图片描述

更多推荐