The examples in this article describe the Java two singleton pattern usages. Share to everyone for your reference, specific as follows:
The single example pattern has two implementations, depending on how it is loaded:
Private: Can only be used in the same class
Static: The class is a class method and cannot invoke an instance method. /Class Global variables
Final: Method or member variable cannot be decorated
1, a hungry man type
public class eagersigleton{
private static final Eagersigleton instance=new Eagersigleton ();
Private Eagersigleton () {}////method public
Eagersigleton getinstance () {//static factory method return
instance;
}
2, lazy type
public class lazysigleton{
private static final Lazysigleton instance=null;
Privacy Lazysigleton () {}//Private constructor public
synchronized Lazysigleton getinstance () {//static factory method, note here synchronized
if (instance==null) {
instance=new Lazysigleton ();
}
return instance
}
}
Analysis and comparison:
Same point:
The singleton pattern belongs to the creation pattern, ensuring that only one instance of the class exists in the same JVM. In the above two types of single case patterns, you can see that:
① the constructors of both methods are private.
② external interfaces are factory methods.
Different points:
The A Hungry man type is the instance that gets the class directly when the class is loaded, and can be said to be binding earlier. The lazy type does not point to a specific object when the class loads. Instead, it is instantiated when the factory method is invoked. Therefore, the former is fast and the latter is slow. But the latter can load other classes (i.e., dynamic extensions) with high flexibility.
More Java-related content readers who are interested can view the website topics: "Java Data structure and algorithm tutorial", "Java Operation DOM node skills summary", "Java file and directory operation tips Summary" and "Java Cache operation Tips"
I hope this article will help you with Java programming.