概念
单例模式是一个类模板,在整个系统运行过程中,有且只有一个实例,且只能New一个。
保证单例的技术方案
1、饿汉式
在使用单列之前就产生了,不管你用不用都先new 出来,避免线程安全。(用的少,不存在线程安全问题)
public class Hungry {
//私有构造方法
private Hungry(){}
//代码执行顺序
//先静态、后动态
//先属性、后方法
//先上、后下
private static final Hungry hungry = new Hungry();
public static Hungry getInstance(){
return hungry;
}
}
2、懒汉式
默认在加载的时候不实例化,在需要用到这个实例的时候在实例化(延时加载),
2.1静态内部类实现单例
public class LazySingleton {
private LazySingleton(){}
//静态内部类
private static class LazyHolder{
private static final LazySingleton LAZY = new LazySingleton();
}
public static final LazySingleto