The purpose of a single example is to ensure that a class has only a single instance, meaning that you cannot create a new instance of the class by using new.
The benefit of a single example: When an object can have only one instance inside the program, it guarantees that we don't create it repeatedly, but always point to the same object.
Singleton by restricting the construction method to private, the class is instantiated externally, and within the same virtual machine scope, the only instance of Singleton can be accessed through the getinstance () method.
First: Instantiate (also known as a Hungry Man singleton mode) when declaring a variable, the code is as follows:
public class Singleton {
private static Singleton instance = new Singleton (); has been instantiated by itself
Private Singleton () {}//proprietary default construction
public static Singleton getinstance () {//Static factory method
return instance;
}
}
The second: Put the creation of the object into the method (also known as the lazy single case pattern), the code is as follows:
public class Singleton {
private static Singleton instance = NULL;
Private Singleton () {}
public static synchronized Singleton getinstance () {
You can also write this: synchronized public static Singleton getinstance () {
if (instance = = null) {
Instance = new Singleton ();
}
return instance;
}
}
Their pros and cons:
The first type of a hungry man:
Advantages: When the class load initialization to create the object, call getinstance, there is no synchronization method, Run-time performance is high.
Disadvantages: Class loading is slow and takes up too much resource space.
The second type of idler:
Advantages: Avoid the shortcoming of the first way, at the same time, can run safely under multithreading.
Disadvantage: Because he uses the lock, the efficiency is slow in the operation.