单例模式 发表于 2018-04-13 如果一个类比较特殊,实例只能有一个,不能让调用方自行new来创建对象,而是提供一个接口来返回该实例。这种设计理论被称为单例模式。 懒汉式1234567891011121314151617181920212223public class Singleton { private static Singleton singleton; private Singleton() { } //懒汉式线程不安全 public static Singleton getSingleton() { if (singleton == null) { singleton = new Singleton(); } return singleton; } //懒汉式线程安全 public static synchronized Singleton getSingleton2() { if (singleton == null) { singleton = new Singleton(); } return singleton; }} 饿汉式123456789101112public class Singleton { private static Singleton singleton = new Singleton(); private Singleton() { } public static Singleton getSingleton() { return singleton; }} 静态内部类1234567891011121314public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton() { } public static Singleton getSingleton() { return SingletonHolder.INSTANCE; }}