单例模式
保证一个类只有一个实例,并且提供一个全局的访问点。
package com.hml.singleton; /** * 饿汉式 */ public class Singleton { private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance () { return instance; } }
package com.hml.singleton; /** * 懒汉式 */ public class Singleton2 { private static Singleton2 instance; private Singleton2() {} public static Singleton2 getInstance() { if (instance == null) { instance = new Singleton2(); } return instance; } }
package com.hml.singleton; /** * 双重锁定 */ public class Singleton3 { private static Singleton3 instance; private Singleton3(){} public static Singleton3 getInstance() { if (instance == null) { synchronized (Singleton3.class) { if (instance == null) { instance = new Singleton3(); } } } return instance; } }
单例模式的重点是: 构造方法私有 提供一个静态方法返回实例