<> What is singleton mode ?

Singleton mode (Singleton) Is the most common and simplest design pattern , Its purpose is to generate only one instance of a class globally .

<> What is the mode of combining field with single instance

There is often a need for multi task information sharing in applications , For example, in the example of train ticket sales , Multiple ticket windows actually share a ticket pool . If a ticket pool uses a class , Then this class can only use one instance , Otherwise, multi task will cause the problem of resource synchronization .

in addition , Frequently created and destroyed objects can also use a fixed instance , The advantage of this is to save the overhead of repeated creation and destruction of memory , Improve the stability of the program .

Object oriented programming is easy to implement singleton models , such as Java,C++ wait , This paper uses Java Code explanation .

The core idea of the singleton model is : Construction method of privatization , Open only static access methods .

<> Implementation of singleton pattern (Java)

<> Hungry Han style
// A single example of hungry Han style public class SingletonHungry { // Actively create static private instances private static
SingletonHungry singleton= new SingletonHungry(); // Private construction method private
SingletonHungry(){} // Static public instance acquisition method public static SingletonHungry getInstance(){
return singleton; } }
You can understand the example of the hungry Chinese style , No matter three, seven, twenty-one, create the object first , Different processes through getInstance Get the same object , So it's thread safe .

But there's a bad thing about it , If a class creation process will consume a lot of resources , But it has not been called during the running of the program getInstance
method , Then there is a waste of resources , If there are many such cases in a system, the system may have performance problems .

therefore , We need a delayed loading feature .

<> Sluggard
public class SingletonLazy { private static SingletonLazy instance; private
SingletonLazy(){} public static SingletonLazy getInstance() { if (instance ==
null) { instance = new SingletonLazy(); } return instance; } }
The lazy man style has been improved on the basis of the hungry man , Judge first instance Is it empty , If empty, create an example , Otherwise, return directly .

Lazy man achieved the delay loading , Ideal for single threading .

But there are problems with multithreading , If multiple threads call at the same time getInstance method , There may be simultaneous judgment instance
Whether the variable is empty , In the above code, it is easy to create multiple instances repeatedly , This goes against the purpose of the singleton pattern .

generally speaking , We'll do some synchronization .

<> Double check lock (DCL,double-checked locking)
public class SingletonDCL { private volatile static SingletonDCL instance;
private SingletonDCL (){} public static SingletonDCL getInstance() { if (
instance== null) { synchronized (SingletonDCL.class) { if (instance == null) {
instance= new SingletonDCL(); } } } return instance; } }
DCL Twice instance The judgment of , And use keywords synchronized .

Imagine when multiple threads call at the same time getInstance Time , There may be simultaneous judgments instance Empty case .

But because synchronized The existence of keywords , Only one thread can enter the code synchronization area at the same time , Other threads will be blocked .

When a blocked thread regains access to the code critical area , Judge again instance Just fine .

<> Static inner class
public class Singleton { private static class SingletonHolder { private static
final Singleton INSTANCE = new Singleton(); } private Singleton (){} public
static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
This method can also delay loading , But it is different from the hungry Han style .

Because only calls are made getInstance Time ,SingletonHolder Will be initialized .

Before Android Development time , When it comes to image cache loading, we often see that there are various open source components ImageHolder Code for , That's how it works .

<>Android Singleton model in source code

with Android System version is 9.0.0 Code as an example , its framework There is one in the bag Singleton.java file .
package android.util; /** * Singleton helper class for lazily initialization.
* * Modeled after frameworks/base/include/utils/Singleton.h * * @hide */ public
abstract class Singleton<T> { private T mInstance; protected abstract T create()
; public final T get() { synchronized (this) { if (mInstance == null) {
mInstance= create(); } return mInstance; } } }
It is an abstract class , And supports generics , Thus, it supports the templating form to create singleton of any type of object .

The source code is very simple , adopt DCL Lazy loading is realized .

Let's take a closer look .

xref: /frameworks/base/core/java/android/app/ActivityManager.java
/** * @hide */ public static IActivityManager getService() { return
IActivityManagerSingleton.get(); } private static final Singleton<
IActivityManager> IActivityManagerSingleton = new Singleton<IActivityManager>()
{ @Override protected IActivityManager create() { final IBinder b =
ServiceManager.getService(Context.ACTIVITY_SERVICE); final IActivityManager am =
IActivityManager.Stub.asInterface(b); return am; } };
ActivityManager yes Android One of the core system services , Its code is 4000 Multi line , It's part of the code . It's through a hidden getService
Call to create .

The creation process is through the above Singleton realization .

From this point of view ,Android Framework The code is not very difficult, is it , believe oneself , You can also write a lot of similar code .

Technology
©2019-2020 Toolsou All rights reserved,
c Language implementation 《 Student management system 》 No hole is the future of mobile phone ? There are still many problems to be solved Junior , A little sense , Just for mutual encouragement How to use Vue Used in Echarts Visual Library The 11th Blue Bridge Cup Java The second provincial competition B Group part Python- be based on OpenCV Contour fill for flooding algorithm hole filling 【C#】 The realization of student achievement information management system List Common interview questions in the collection and simple ideas China Mobile Science Popularization : Why do mobile networks call “ Cellular mobile network ”【Golang Basic series 10 】Go language On conditional sentences if