图解设计模式(Creational)-Singleton 5/23 发表于 2019-01-25 分类于 java 只有一个实例 示例代码饿汉模式123456789101112public class Singleton1 { private static Singleton1 instance = new Singleton1(); private Singleton1() { } public static Singleton1 getInstance() { return instance; }} 懒汉模式(线程不安全)12345678910111213141516public class Singleton2 { private static Singleton2 instance; private Singleton2() { } public Singleton2 getInstance() { if (instance == null) { instance = new Singleton2(); } return instance; }} 懒汉模式(双检锁、线程安全)12345678910111213141516171819public class Singleton3 { private static volatile Singleton3 instance; private Singleton3() { } public Singleton3 getInstance() { if (instance == null) { synchronized (Singleton3.class) { if (instance == null) { instance = new Singleton3(); } } } return instance; }} 枚举12345public enum Singleton4 { instance;}