单例模式
介绍
单例模式就是确保一个类只有一个唯一的实例对象,系统中某些类只有一个实例是很重要的,例如,配置文件,只有一个实例,保证大家引用的是同一个配置;一些类的初始化过程很复杂,只需要初始化一次,减少资源消耗
实现单例模式的要点
1、构造函数要私有化
2、类要自己创建这个实例
3、类要提供获取这个实例的方法
4、防止反序列化生成多个实例
常见的几种单例模式的实现方式
1、

在类加载的时候就创建了实例,避免的多线程同步的问题,但没有达到懒加载的效果。
2、

在具体调用的时候才创建实例,实现了懒加载效果,也保证了多线程下的同步,代码稍微复杂点。
3、

枚举可以避免多线同步问题,也能防止反序列化创建新的对象,但是很少使用。可能是因此枚举无法继承或实现其他的类或接口。
4、

由一个Map来存储对象实例,使用的时候再创建实例对象,存到map中,下次则直接从map中获取。也实现了懒加载,但是也要确保SingletonManager是唯一的,通常都是由应用的上下文如application来管理SingletonManager对象。
单利模式在项目中的应用
在把一个布局文件转为视图组件的时候,常常会实现这样的实现
LayoutInflater.from(context).inflate(R.layout.activity_h_scrollview,null);
这里LayoutInflater对象的创建就是一种单例模式。来看下源码的实现:

context是一个抽象类,而他的实现类ContextImpl则会调用SystemServiceRegistry.getSystemService(this, name);在来看下具体实现

SYSTEM_SERVICE_FETCHERS:是一个静态的HashMap,存储ServiceFetcher,保证只有一个实例

====================衍生=======================
ServiceFetcher:从名字看是一个服务的获取器,他的定义和实现都在SystemServiceRegistry类中。他是一个接口有多种实现,分别定义不同类型的服务的获取,比如
CachedServiceFetcher:

mServiceCache是ContextImpl对象创建的时候创建的

因此每个context实例都保存着一份service缓存
StaticServiceFetcher

mCachedInstance在保存在当前对象中,而ServiceFetcher存在静态的HashMap中的,一个类型只有一个对象,因此也保证的对象的唯一。
StaticApplicationContextServiceFetcher

和StaticServiceFetcher一样,也只会有一个对象。