一个单一的类,负责创建自己的对象,同时确保系统中只有单个对象被创建

单例特点

  • 某个类只能有一个实例;(构造器私有)
  • 它必须自行创建这个实例;(自己编写实例化逻辑)
  • 它必须自行向整个系统提供这个实例;(对外提供实例化方法)

    饿汉式

    1. public class Runtime {
    2. private static final Runtime currentRuntime = new Runtime();
    3. public static Runtime getRuntime() {
    4. return currentRuntime;
    5. }
    6. /** Don't let anyone else instantiate this class */
    7. private Runtime() {}
    8. }

懒汉式

  1. public class Singleton {
  2. private volatile static Singleton singleton;
  3. private Singleton (){}
  4. public static Singleton getSingleton() {
  5. if (singleton == null) {
  6. synchronized (Singleton.class) {
  7. if (singleton == null) {
  8. singleton = new Singleton();
  9. }
  10. }
  11. }
  12. return singleton;
  13. }

应用场景

  • 多线程中的线程池
  • 数据库的连接池
  • 系统环境信息
  • 上下文(ServletContext)