Singleton in Java
First (hunger Singleton mode): instantiate a variable when it is declared
Public class Singleton {// automatic instantiation of static initialization private static Singleton instance = new Singleton (); // No parameter constructor private Singleton (){}
Public static Singleton getInstance () {return instance ;}}
Advantage: an object is created when the class is loaded and initialized. When getInstance is called, there is no synchronization method and the runtime performance is high.
Disadvantage: the class loading speed is slow, occupying too much resource space.
Second (lazy Singleton mode): place object creation in the Method
public class Singleton {
private static Singleton instance = null;
private Singleton(){} public static synchronized Singleton getInstance() { if (instance == null){
instance = new Singleton();
} return instance; } }
Advantage: This avoids the disadvantages of the first method, and can run safely under multiple threads.
Disadvantage: It is slow in running because it uses a lock.
Summary:
The role of Singleton mode:
Ensure that a class has only one instance, that is, you cannot create a new instance of this class through new.
When an object can only have one instance in the program, it can ensure that we do not create it again, but always point to the same object.
Singleton limits the constructor to private to avoid class instantiation outside. Within the same Virtual Machine range, Singleton's unique instance can only be accessed through the getInstance () method.
The role of the parameter-free constructor is:
Each class must have at least one constructor. If you build a constructor with parameters, you can write a constructor without any parameters, however, when you try to build a new constructor with no parameters, the compiler will report an error because the constructor without parameters cannot be found.
That is to say, when you do not provide a constructor to a class, the compiler will automatically add a constructor without parameters. If so, the compiler will not. You need to display and write the constructor without parameters.