使用前提:
需要频繁的进行创建和销毁的对象,创建对象时耗时过多或耗费资源过多
三要素:
- 1、构造方法私有化;
- 2、实例化的变量引用私有化;
- 3、获取实例的方法共有。
1.饿汉式单例
弊端:在类装载的时候就完成实例化
/** * 饿汉式单例 * * @author Wonder * @history create Wonder 2018年10月24日 上午9:55:32 * @version 1.0 */ public class Singleton1 { private Singleton1() { }// 1私有化构造 private final static Singleton1 singleton1 = new Singleton1();// 2实例化 public static Singleton1 getInstance() {// 3对外提供 return singleton1; } }