/饿汉式 public class EagerSingleton { //一上来就创建实例,所以叫饿汉 private static final EagerSingleton m_instance = new EagerSingleton(); private EagerSingleton() { } public static EagerSingleton getInstance() { return m_instance; } } //懒汉式 public class LazySingleton { private static LazySingleton m_instance = null; private LazySingleton() { } synchronized public static LazySingleton getInstance(){ //实例为空的时候才创建,否者直接拿来用,所以是懒汉 if (m_instance == null) { m_instance = new LazySingleton(); } return m_instance; } }
用java 写一个Singleton
最新推荐文章于 2021-03-08 01:40:39 发布