单例模式
<pre><code> InputMethodManager(IInputMethodManager service, Looper looper) {
mService = service;
mMainLooper = looper;
mH = new H(looper);
mIInputContext = new ControlledInputConnectionWrapper(looper,
mDummyInputConnection, this);
}
/**
* Retrieve the global InputMethodManager instance, creating it if it
* doesn't already exist.
* @hide
*/
public static InputMethodManager getInstance() {
synchronized (InputMethodManager.class) {
if (sInstance == null) {
IBinder b = ServiceManager.getService(Context.INPUT_METHOD_SERVICE);
IInputMethodManager service = IInputMethodManager.Stub.asInterface(b);
sInstance = new InputMethodManager(service, Looper.getMainLooper());
}
return sInstance;
}
}
客户端调用,比如contextimpl中的getSystemService()方法中如下调用:
class ContextImpl extends Context{
@Override
public Object getSystemService(String name) {
if (WINDOW_SERVICE.equals(name)) {
//... ... 省略下面n个if,else if
} else if (INPUT_METHOD_SERVICE.equals(name)) {
//获取输入法管理者唯一实例
return InputMethodManager.getInstance(this);
} else if (KEYGUARD_SERVICE.equals(name)) {
//... ... 省略下面n个if,else if
} else if (ACCESSIBILITY_SERVICE.equals(name)) {
//又见单例,无处不在
return AccessibilityManager.getInstance(this);
} else if (LOCATION_SERVICE.equals(name)) {
//... ... 省略下面n个if,else if
} else if (NFC_SERVICE.equals(name)) {
return getNfcManager();
}
return null;
}
} </code></pre>