This article describes the usage of two singleton patterns in Java. Share it for your reference, as follows:
According to the loading method, there are two implementations of singleton mode:
private: Only used in the same class
static: This class is a class method and cannot call instance methods. /Class Global Variable
Final: Method or member variable cannot be modified
1. Hungry Man Style
public class EagerSigleton{private static final EagerSigleton instance=new EagerSigleton();private EagerSigleton(){}////Private constructor public EagerSigleton getInstance(){// Static factory method return instance;}}2. Lazy style
public class LazySigleton{private static final LazySigleton instance=null;private LazySigleton(){}//Private constructor public synchronized LazySigleton getInstance(){//static factory method, note the synchronizedif(instance==null){instance=new LazySigleton();}return instance;}}Analysis and comparison:
Similarities:
Singleton pattern belongs to the creation pattern, ensuring that only one instance of this class exists in the same jvm. In the above two singleton patterns, it can be seen:
① The constructors of both methods are private.
② External interfaces are all factory methods.
Differences:
The Hungry Style directly gets an instance of this class when the class is loaded. It can be said that the formula is bound in the early stage. The lazy style does not point to a specific object when the class is loaded. Instead, it is instantiated after the factory method is called. Therefore, the former is fast and the latter is slow. But the latter can load other classes, which are highly flexible (that is, dynamic expansion).
For more Java-related content, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.