Three methods for declaring a singleton class:
Package com. twoslow. cha2;/*** you can call the private constructor through the accessibleobject. setaccessible () reflection mechanism. * @ Author sai **/public class singleton01 {private singleton01 () {} public static final singleton01 instance = new singleton01 (); Private object readresolve () {return instance ;}}
Package com. twoslow. cha2;/*** you can call the private constructor through the accessibleobject. setaccessible () reflection mechanism. * @ Author sai **/public class singleton02 {private singleton02 () {} Private Static final singleton02 instance = new singleton02 (); public static singleton02 getinstance () {return instance ;} private object readresolve () {return instance ;}}
Package com. twoslow. cha2;/*** it is not enough to add implements serializable to the Declaration to achieve single-instance class serialization. * All instance domains must be declared as transient and a readresolve method is provided. Otherwise, * a new instance is created every time a serialized instance is deserialized. * The Enumeration type of a single element provides a serialization mechanism, which is the best way to implement Singleton. * @ Author sai **/Public Enum singleton03 {instance ;}
Chapter 2: create and destroy objects. Item3: Use a private constructor or enumeration type to enhance the singleton attribute.