/** * The second method of implementing Singleton, a common member is a static factory method. * (the public static member in the first method is a final domain, that is, the direct use of private static final Singleton INSTANCE = new Singleton ();) * @author Liu Xiangfeng * */ Public class Singleton { Private Static FinalSingleton INSTANCE =NewSingleton ();/** * Privileged clients can use Java.lang.reflect.AccessibleObject.setAccessible (Array,flag), and private constructs are invoked through a reflection mechanism. * To protect against this attack, you can modify the constructor, which throws an exception when it is required to create a second instance * / Private Singleton() {//Avoid accidentally calling the constructor inside the class Throw NewAssertionerror (); } Public StaticSingletongetinstance() {returnINSTANCE; } Public void leavethebuilding() { }}/** * after Java 1.5. Simply write an enumeration type that contains a single element to implement Singleton. * Provides a free serialization mechanism that absolutely prevents multiple instantiations, even in the face of complex serialization or reflection attacks. * Single-element enumeration types have become the best way to implement Singleton. * @author Liu Xiangfeng * * * * Public enumEnumsingleton {INSTANCE; Public void leavethebuilding(){}}/** * Serialization of Singleton mode * @author Liu Xiangfeng * */ Public class Serializesingleton implements Serializable { //Declare all instance domains to be instantaneous transient Private Static FinalSerializesingleton INSTANCE =NewSerializesingleton ();//Provides a readresolve method, otherwise a new instance is created each time a serialized instance is deserialized PrivateObjectReadresolve(){returnINSTANCE; }Private Serializesingleton() {Throw NewAssertionerror (); } Public StaticSerializesingletongetinstance() {returnINSTANCE; } Public void leavethebuilding() { }}
Hardening the Singleton property with a private constructor or enumeration type--effective Java reading notes