singleton pattern
Only one object of a class can exist in memory
Note: In order to prevent other programs from creating the object too much, first control and prohibit other programs from creating objects of this class, then customize a private object in the class, and finally provide a method to access the private object.
The code implementation is divided into three steps: (1) Constructor privatization. (2) Create a private object of this class in the class. (3) Provide a method for obtaining the object externally.
Next, let's talk about the classification of singleton mode: hungry mode (recommended), full mode (thread unsafe)
/** * Hungry mode * Objects are created when the class is created */ class SingleDemo1{ private int a; private SingleDemo1(){} private static SingleDemo1 s1 = new SingleDemo1(); public static SingleDemo1 getInstance(){ return s1; } public int getA() { return a; } public void setA(int a) { this.a = a; } } /** * Lazy mode * The object is created when the object is called * Due to multi-threading technology, the lazy mode may be unsafe */ class SingleDemo2{ private SingleDemo2(){} private static SingleDemo2 s2 = null; public static SingleDemo2 getInstance(){ if(s2==null){ s2 = new SingleDemo2(); } return s2; } }
Test Results:
public class Test { public static void main(String[] args) { /* * The two variables single1 and single2 refer to the same object */ SingleDemo1 single1 = SingleDemo1.getInstance(); SingleDemo1 single2 = SingleDemo1.getInstance(); single1.setA(10); System.out.println(single2.getA()); //10 } }