Singleton mode

Ensure that a class has one and only one object , Avoid generating multiple objects and consuming too many resources , Or there should be only one and only one object of a certain type . for example , Creating an object consumes too many resources , To access IO And databases , This is to consider the use of singleton mode .

By privatizing the constructor of the singleton class , Makes the outer class unavailable new The object of the singleton class is constructed manually . The singleton class exposes a public static method , It is used to obtain the unique object of the singleton class , In the process , To ensure that there is only one object in the singleton class in a multithreaded environment .

Here are three singleton patterns :

* Lazy man model
* The model of the hungry man
* Recommendation mode

Lazy man model

// Lazy man model private static Singleton instance; private Singleton(Context context){
} public static synchronized Singleton getInstance(Context context) {
if(instance==null){ instance = new Singleton(context); } return instance; }
Lazy man mode is added to the static method synchronized keyword , Synchronize methods , But every time a method is called, it synchronizes , Consume unnecessary resources , Naturally, this approach is not recommended .
The model of the hungry man

// The model of the hungry man private static Singleton instance = new Singleton(); private
Singleton(){ } public static synchronized Singleton getInstance() { return
instance; }
The starvation mode removes the synchronization keyword , By initializing the object instance at declaration time . But imagine it , Multiple singleton patterns in the project , Users may not use it , This initialization results in unnecessary resource consumption .
Recommendation mode

// Recommendation mode private Singleton(){ } public static Singleton getInstance() { return
SingletonHolder.instance; } private static class SingletonHolder{ private
static final Singleton instance = new Singleton(); }

When loading for the first time Singleton Class time , The object is not initialized . This approach does not guarantee thread safety , It can also guarantee the uniqueness of singleton , It also delays the instantiation of the singleton . So this paper recommends this model .

©2019-2020 Toolsou All rights reserved,
One is called “ Asking for the train ” A small village Finally got the train Spring Boot Lesson 16 :SpringBoot Implementation of multithreading with injection class Chrome OS, For programmers and Windows What does it mean ? Internet Marketing JAVA Convert a string to a numeric type I've been drinking soft water for three years ? What is the use of soft water and water softener You don't know ——HarmonyOS Talking about uni-app Page value transfer problem JavaScript Medium Call and ApplySparkSQL Achieve partition overlay write Character recognition technology of vehicle license plate based on Neural Network