单例模式在Android源码中的应用
除了之前说的几种单例的实现方式之外还可以使用容器来实现。
public class SingletonManager {
private static final Map<String, Object> instanceMap = new HashMap<String, Object>();
public static void register(String key, Object obj) {
instanceMap.put(key, obj);
}
public static Object get(String key) {
return instanceMap.get(key);
}
}
在Android的系统服务创建时在使用了这个方法以保证任务的单例,并提供给我们使用。以LayoutInflater为例。

可以看到context.getSystemService方法是Context提供给我们获取服务的方法。

在Context的实现类ContextImpl中可以找的方法的实现。

在SystemServiceRegisty类中可以发现SYSTEM_SERVICE_FETCHERS(静态的HashMap<String, ServiceFetcher<?>>)可以获取到一个ServiceFetcher<?>对象,在通过这个对象的getService方法获取到相应的服务。
SystemServiceRegisty类是被final修饰的类无法被继承,并且私有了构造方法。其中有一个静态方法是用于注册服务的也就是把ServiceFetcher<?>放入HashMap中去。

由于这个方法是私有的,就导致注册的操作必须在这个类中完成。所以所有服务的创建都在这个类的静态代码块中完成。

以上就是Android中实现服务单例的过程。
网友评论