getSystemService是Context中的方法,經過SystemServiceRegistry類獲取SystemService實例,具體的實如今ContextImpl中。有關Context的簡介,能夠參考http://www.javashuo.com/article/p-yegqpqxb-hz.htmljava
@Override public Object getSystemService(String name) { return SystemServiceRegistry.getSystemService(this, name); }
一、SystemServiceRegistry中聲明瞭兩個靜態HashMap設計模式
// Service registry information. // This information is never changed once static initialization has completed. private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES = new HashMap<Class<?>, String>(); private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS = new HashMap<String, ServiceFetcher<?>>();SYSTEM_SERVICE_NAMES存放着SystemService的class和名稱;ide
SYSTEM_SERVICE_FETCHERS存放着SystemService的名稱和接口ServiceFetcher的實例。fetch
二、在SystemServiceRegistry類加載時會建立服務實例並經過registerService方法將ServiceFetcher存放在HashMap中。this
ServiceFetcher是一個用來獲取Service實例的接口:spa
/** * Base interface for classes that fetch services. * These objects must only be created during static initialization. */ static abstract interface ServiceFetcher<T> { T getService(ContextImpl ctx); }static { registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class, new CachedServiceFetcher<AccessibilityManager>() { @Override public AccessibilityManager createService(ContextImpl ctx) { return AccessibilityManager.getInstance(ctx); }}); // 省略代碼 }/** * Statically registers a system service with the context. * This method must be called during static initialization only. */ private static <T> void registerService(String serviceName, Class<T> serviceClass, ServiceFetcher<T> serviceFetcher) { SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName); SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher); }
三、調用getSystemService時根據名稱從HashMap獲取實例.net
/** * Gets a system service from a given context. */ public static Object getSystemService(ContextImpl ctx, String name) { ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name); return fetcher != null ? fetcher.getService(ctx) : null; }
SystemService的兩個靜態HashMap其實就是「使用容器實現單例」設計
有關單例模式能夠參考:http://www.javashuo.com/article/p-riuvmrsx-ht.htmlcode