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 .
Technology
Daily Recommendation