Singleton refers to a class that is instantiated only once. Typically used for classes that create very expensive resources or require only one instance of the system. This is very common. Remember the previous internship interview when there is this face test. The general approach is to privatize the constructor, then provide a static variable, and then provide a static public method to return the static instance:
Singleton with static Factorypublic class Elvis {private static final Elvis INSTANCE = new Elvis ();p rivate Elvis () {}pub Lic static Elvis getinstance () {return INSTANCE;} public void Leavethebuilding () {}}
This is the A hungry man pattern in the Singleton factory method pattern, and there is a lazy pattern. is to instantiate later. It's not going to be written. To be reminded, a privileged client can invoke a private constructor through a reflection mechanism. That is the violent reflex that is usually said. Refer to my other article: Java violence reflex. If you need to defend against this attack, you can modify the constructor so that it throws an exception when it is asked to create a second instance. In addition to the factory method there is a public domain method:
public class Elvis2 {public static final Elvis2 INSTANCE = new Elvis2 ();p rivate Elvis2 () {}public void leavethebuilding () {} }
The advantages of this approach are clear and unambiguous. The disadvantage is rigid, performance is not. The advantage of factory method is flexibility. The disadvantage is that it can be easily modified, such as changing to a unique instance of each thread that invokes the method. In addition, these two methods make this class more cumbersome to be serializable .... So the third way:
public enum ELIVIS3 {instance;public void leavethebuilding () {}}
This method is functionally similar to the public domain approach, but it is more concise. Provides a free serialization mechanism that absolutely prevents multiple instantiations, even in the face of complex serialization or reflection attacks. Although this approach is not widely used, the enumeration types of elements have become the best way to implement Singletong!
Reading notes of "effective Java" Third, strengthen the Singleton property with a private constructor or enumeration type