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,
【 Explain in detail 】 Interview must ask :SpringBoot Automatic configuration principle 【 Hyper detail 】Java Realization of student information management system 2020 The 11th National Blue Bridge Cup Python group JavaScript note ( five )---- Branch statement MYSQL database SQL Sentence practice experiment EXERCISES. 1 SIMPLE COMMANDSMySQL Basics Commonly used sentence ( Add / delete / modify query )C++ of string of compare usage vue limit input Only positive numbers can be entered C Language of a Gobang game implementation Programmer refused due to low salary offer,HR become shame , Netizens instantly blew up ..