Java Singleton Mode
Concept: java Singleton mode is a common design mode. The Singleton mode can be written in several ways. Here we mainly introduce three types: the lazy singleton and ELE. Me Singleton modes have the following features: 1. A singleton class can only have one instance. 2. The Singleton class must create its own unique instance. 3. The Singleton class must provide this instance to all other objects. I. Lazy Singleton
public class Singleton { private static Singleton uniqueInstance = null; private Singleton() { // Exists only to defeat instantiation. } public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } // Other methods...}
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. (In fact, the Java reflection mechanism can be used to instantiate classes whose constructor is private, which will basically invalidate all Java Singleton implementations. We will not discuss this issue here, so we may think that the reflection mechanism does not exist .) Ii. Hunger examples
// Lazy Singleton type. in the first call, instantiate your own public class Singleton {// private default constructor private Singleton () {}// note that there is no final private static Singleton single = null; // static factory method public static Singleton getInstance () {if (single = null) {single = new Singleton () ;}return single ;}}
When the class is created, a static object has been created for the system. It will not be changed in the future, so it is inherently thread-safe.