1. Concept
The so-called singleton pattern is to ensure that only one instance of the class exists in the entire application. Just like the application in the Java Web, it provides a global variable, which is quite useful, such as saving global data and implementing global operations.
2. Realization
The simplest implementation is to set the constructor of the class to private , so as to ensure that other classes cannot directly create new instances. Then provide a static instance in the class to return to the caller, so that there is only one instance.
package singleton pattern; /** * Created by shyroke on 2018/4/23. */ public class SingleTon { private static final SingleTon newInstance = new SingleTon(); private SingleTon(){} public SingleTon newInstance(){ return newInstance; } public static void main(String[] args) { SingleTon s1 = SingleTon.newInstance; SingleTon s2 = SingleTon.newInstance; System.out.println(s1); System.out.println(s2); } }
The result is as shown below, the reference address is the same, indicating that it is the same object.