单例模式有八种方式:

  • 饿汉式(静态常量)
  • 饿汉式(静态代码块)
  • 懒汉式(线程不安全)
  • 懒汉式(线程安全,同步方法)
  • 懒汉式(线程安全,同步代码块)
  • 双重检查
  • 静态内部类
  • 枚举

注意事项和细节说明

  1. 单例模式保证了系统内存中该类只存在一个对象节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能。
  2. 当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用 new
  3. 单例模式使用的场景:需要频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级对象),但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象(比如数据源、session 工厂等)

    JDK 源码

  1. public class Runtime {
  2. private static Runtime currentRuntime = new Runtime();
  3. /**
  4. * Returns the runtime object associated with the current Java application.
  5. * Most of the methods of class <code>Runtime</code> are instance
  6. * methods and must be invoked with respect to the current runtime object.
  7. *
  8. * @return the <code>Runtime</code> object associated with the current
  9. * Java application.
  10. */
  11. public static Runtime getRuntime() {
  12. return currentRuntime;
  13. }
  14. /** Don't let anyone else instantiate this class */
  15. private Runtime() {}
  16. //...
  17. //...
  18. }

双重检查

public class Singleton {

    private volatile static Singleton uniqueInstance;

    public Singleton() {
    }

    public static Singleton getUniqueInstance() {
        if (uniqueInstance == null){
            synchronized (Singleton.class){
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }

            }
        }
        return uniqueInstance;
    }
}