单例模式特点:
① 单例类只能有一个实例
② 私有构造方法,不允许通过其他类创建单例类的实例
③ 提供静态get方法返回单实例

饿汉式:类加载的时候就创建实例
懒汉式:类加载时不创建实例,第一次调用get方法时才创建实例

饿汉式优点:简单,调用时速度快,无需考虑创建实例时线程安全问题
饿汉式缺点:占用内存,可能使用该类时只使用了其静态方法,却创建了对象

懒汉式优点:第一次获取实例前占用内存少
懒汉式缺点:需要考虑线程安全,第一次获取实例时要进行初始化工作

饿汉式:

/**
 * 饿汉单例模式
 * 类加载的时候就创建实例
 */
public class SingleInstance1 {
    private static final SingleInstance1 instance = new SingleInstance1();

    //构造方法要私有
    private SingleInstance1() {
        System.out.println("SingleInstance1 实例化了一个单例对象");
    }

    public static SingleInstance1 getInstance() {
        return instance;
    }
}

volatile 关键字:禁止指令重排序(防止虚拟机先分配地址后初始化对象)、对缓存的修改立即写入主存、阻止其他线程对其进行写操作
双重检查锁定:如果同步块中不再次判断是否为null可能会实例化两次。如果两个线程同时执行完成第一个if,其中一个获得锁并实例化了对象,然后另一个线程进入同步块不会再次判断是否为null,而再次实例化。

懒汉式:使用 synchronized

/**
 * 懒汉单例模式
 * 初始时不创建实例,第一次调用get方法时才创建实例
 */
public class SingleInstance2 {
    //使用 volatile 修饰单实例
    private volatile static SingleInstance2 instance;

    //构造方法要私有
    private SingleInstance2() {
    }

    public static SingleInstance2 getInstance() {
        if (instance == null) {
            synchronized (SingleInstance2.class) {
                if (instance == null) {
                    instance = new SingleInstance2();
                    System.out.println("SingleInstance2 实例化了一个单例对象");
                }
            }
        }
        return instance;
    }
}

懒汉式:使用 ReentrantLock

/**
 * 懒汉单例模式
 * 初始时不创建实例,第一次调用get方法时才创建实例
 */
public class SingleInstance3 {
    //使用 volatile 修饰单实例
    private volatile static SingleInstance3 instance;
    private static ReentrantLock lock = new ReentrantLock();

    //构造方法要私有
    private SingleInstance3() {
    }

    public static SingleInstance3 getInstance() {
        if (instance == null) {
            lock.lock();
            try {
                if (instance == null) {
                    instance = new SingleInstance3();
                    System.out.println("SingleInstance3 实例化了一个单例对象");
                }
            } finally {
                lock.unlock();
            }
        }
        return instance;
    }
}

静态内部类方式

双重检查太麻烦?可以用静态内部类方式。

  1. 任意类都只会被加载一次,其中的静态代码块也只会执行一次,保证是单例。
  2. 内部类不被调用时不会加载,即饿汉式,避免创建无用单例浪费内存空间。
  3. 类加载过程是线程安全的,所以无需双重检查。
  4. 内部类可以访问外部类所有方法,包括私有的构造方法
  5. 内部类必须私有化,不允许被修改,由外部类提供获取单例的方法
public class Singleton {
	// 私有化构造方法
	private Singleton() {};

	// 私有静态内部类
	private static class SingletonHolder {
		private static Singleton instance;
		
		static {
			instance = new Singleton();
			System.out.println("单例对象被实例化了");
		}
	}

	// 获取单例
	public static Singleton getInstance() {
		return SingletonHolder.instance;
	}
}