I. BACKGROUND
The so-called singleton is a class that is instantiated only once, and Singleton is usually used to represent the system components that are inherently unique.
There are three ways to implement Singleton:
①. Private constructor, public static final domain.
②. Private builder, public static factory method.
③. Single element enumeration type (preferred).
Second, private constructor, public static final domain
public class Singleton1 {common static
final Singleton1 INSTANCE = new Singleton1 ();//publicly static final domain
*
* Private constructor
* *
private Singleton1 () {
}
}
Third, private constructors, public static factory methods
Disadvantage 1: A privileged client can invoke a private constructor by means of a reflection mechanism, and if it is necessary to defend against such an attack, modify the constructor so that it throws an exception when it is required to create a second instance of the accessibleobject.setaccessible.
public class Singleton2 {
private static final Singleton2 INSTANCE = new Singleton2 ();//private static final domain
*
* Private Construction
* * Private Singleton2 () {
}
* * public static Factory Method * * *
() () () () () () () (Singleton2) getinstance C11/>return INSTANCE
}
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/
Disadvantage 2: Each time a serialized instance is deserialized, a new instance is created, in order to prevent this, not only to implement the Serializable interface, but also to provide a readresolve method.
public class Singleton2 implements Serializable {
private static final long serialversionuid = 1L;
private static final Singleton2 INSTANCE = new Singleton2 (); Private static final domain
/* Private constructor
/privacy
Singleton2 () {
}
* * public static Factory method *
* Static Singleton2 getinstance () {return
INSTANCE;
}
* * Deserialization ensures only one instance/public
Object readresolve () {return
INSTANCE}}
}
Iv. Single-Element enumeration types
Best practices: More concise, free serialization mechanism, absolutely prevent multiple instantiation, even in the face of complex serialization or reflection attacks.
public enum Singleton3 {
INSTANCE;
public void Testsingleton () {
System.out.println ("Testsingleton");
}
public static void Main (string[] args) {
Singleton3.INSTANCE.testSingleton ();
}
}
Author: csdn Blog zdp072