Android design mode-perfect Singleton Mode
Android perfect Singleton mode:
The previous Singleton mode was not fully considered;
This problem was obtained during the interview;
Even with such a problem, we can see that the examples we write are too naive;
So I found some information on the Internet and wrote another one;
Package com. example. demo; public class HttpUtils {// volatile is used as the command keyword to ensure that this command is not omitted due to compiler optimization, and the value must be read directly each time. // a variable defined as volatile means that this variable may be unexpectedly changed. // in this way, the compiler will not assume the value of this variable. // Precisely, the optimizer must carefully re-read the value of this variable every time when using this variable, rather than using the backup saved in the register. Private volatile static HttpUtils instance; private HttpUtils () {// constructor logic processing} public static HttpUtils getInstance () {// determines whether it is null for the first time if (instance = null) {synchronized (HttpUtils. class) {// lock // The second time when determining whether the thread is empty and going here at the same time, we need to optimize if (instance = null) {instance = new HttpUtils () ;}} return instance ;}}
Singleton mode, widely used in Android Framework;
For example:
1. InputMethodManager
2. View Distribution Management AccessibilityManager for click, focus, text change, and other events
public final class InputMethodManager { static final boolean DEBUG = false; static final String TAG = "InputMethodManager"; static final String PENDING_EVENT_COUNTER = "aq:imm"; static InputMethodManager sInstance; 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; } } /** * Private optimization: retrieve the global InputMethodManager instance, * if it exists. * @hide */ public static InputMethodManager peekInstance() { return sInstance; }}