Singleton mode definition:
Ensure a class has only one instance, and provide a global point of access to it.
Dynamically ensure that a class has only one instance, and instantiate it and provide the instance to the entire system.
As shown in (from Head First Design Patterns ).
The private constructor ensures that an instance is generated in an application and is self-instantiated (new Singleton () is used in Singleton ()).
What are the advantages of the singleton mode?:
Because the singleton mode only has one instance in the memory, the memory overhead is reduced.
The Singleton mode can avoid multiple resource occupation. For example, when a file is written, because only one instance exists in the memory, you can avoid simultaneous write operations on the same resource file.
In Singleton mode, you can set global access points to optimize and share resource access.
When the singleton mode is used, many issues such as how to prevent simultaneous creation of multiple threads are considered, in Head First Design Patterns, "double-checked locking" is used to reduce the use of synchronization.Copy codeThe Code is as follows: public class Singleton {
/* The volatile keyword ensures that multiple threads
* Handle the uniqueInstance variable correctly when it
* Is being initialized to the Singleton instance.
**/
Private volatile static Singleton uniqueInstance;
Private Singleton (){}
Public static Singleton getInstance (){
If (uniqueInstance = null ){
Synchronized (Singleton. class ){
If (uniqueInstance = null ){
UniqueInstance = new Singleton ();
}
}
}
Return uniqueInstance;
}
}
In the Android source code, there are many examples that use the singleton mode, such:
I. InputMethodManager class Copy codeThe Code is as follows: public final class InputMethodManager {
Static final boolean DEBUG = false;
Static final String TAG = "InputMethodManager ";
Static final Object mInstanceSync = new Object ();
Static InputMethodManager mInstance;
Final IInputMethodManager mService;
Final loginmmainlogin;
Create a unique static InputMethodManager mInstance instance;Copy codeThe Code is as follows :/**
* Retrieve the global InputMethodManager instance, creating it if it
* Doesn' t already exist.
* @ Hide
*/
Static public InputMethodManager getInstance (Context context ){
Return getInstance (context. getMainLooper ());
}
/**
* Internally, the input method manager can't be context-dependent, so
* We have this here for the places that need it.
* @ Hide
*/
Static public InputMethodManager getInstance (lodomainmainlogoff ){
Synchronized (mInstanceSync ){
If (mInstance! = Null ){
Return mInstance;
}
IBinder B = ServiceManager. getService (Context. INPUT_METHOD_SERVICE );
IInputMethodManager service = IInputMethodManager. Stub. asInterface (B );
MInstance = new InputMethodManager (service, mainlomanager );
}
Return mInstance;
}
Prevents multiple threads from creating instances at the same time:Copy codeThe Code is as follows: synchronized (mInstanceSync ){
If (mInstance! = Null ){
Return mInstance;
}
When no instance object is created, call mInstance = new InputMethodManager (service, mainlogoff );
The class constructor is as follows:Copy codeThe Code is as follows: InputMethodManager (IInputMethodManager service, loopetemediactor ){
MService = service;
Mmainlogoff = logoff;
MH = new H (logoff );
MIInputContext = new ControlledInputConnectionWrapper (logoff,
MDummyInputConnection );
If (mInstance = null ){
MInstance = this;
}
}
Ii. thoppmanager Copy codeThe Code is as follows: public class javasthoppmanager {
Private static final String TAG = "thoppmanager ";
Private static final boolean V = Constants. VERBOSE;
// Create a private static instance
Private static thoppmanager INSTANCE;
/** Used when obtaining a reference to the singleton instance .*/
Private static Object INSTANCE_LOCK = new Object ();
...
/**
* Get singleton instance.
*/
Public static thoppmanager getInstance (Context context ){
Synchronized (INSTANCE_LOCK ){
If (INSTANCE = null ){
INSTANCE = new thoppmanager ();
}
INSTANCE. init (context );
Return INSTANCE;
}
}
Iii. AccessibilityManager classCopy codeThe Code is as follows: public final class AccessibilityManager {
Private static final boolean DEBUG = false;
Private static final String LOG_TAG = "AccessibilityManager ";
/** @ Hide */
Public static final int STATE_FLAG_ACCESSIBILITY_ENABLED = 0x00000001;
/** @ Hide */
Public static final int state_flag_touch_configuration_enabled = 0x00000002;
Static final Object sInstanceSync = new Object ();
Private static AccessibilityManager sInstance;
...
/**
* Get an AccessibilityManager instance (create one if necessary ).
*
* @ Hide
*/
Public static AccessibilityManager getInstance (Context context ){
Synchronized (sInstanceSync ){
If (sInstance = null ){
IBinder iBinder = ServiceManager. getService (Context. ACCESSIBILITY_SERVICE );
IAccessibilityManager service = IAccessibilityManager. Stub. asInterface (iBinder );
SInstance = new AccessibilityManager (context, service );
}
}
Return sInstance;
}
/**
* Create an instance.
*
* @ Param context A {@ link Context }.
* @ Param service An interface to the backing service.
*
* @ Hide
*/
Public AccessibilityManager (Context context, IAccessibilityManager service ){
MHandler = new MyHandler (context. getMainLooper ());
MService = service;
Try {
Final int stateFlags = mService. addClient (mClient );
SetState (stateFlags );
} Catch (RemoteException re ){
Log. e (LOG_TAG, "AccessibilityManagerService is dead", re );
}
}
And so on...
Starting from the first week of the New Year, record your learning process from the simplest Singleton mode ~~~