Singleton Design Patterns
Guarantee Design Patterns: Guarantee that the class has only one object in memory
How to ensure that tears have only one object in memory
Controlling the creation of class hits does not allow other classes to create objects of this class. private
Redefining an object of this class in this class. Singleton s;
Provide a common access method, public static Singleton getInstance () {return s}
1. Hungry Chinese style development in this way
2. Lazy Interview Writing in this Way
Hungry Chinese style is space for time, lazy Chinese style is time for space.
In multithreaded access, hungry Chinese may not create multiple objects, while lazy Chinese may create multiple objects.
casepublic class demo1_Singleton { public static void main(String[] args) { //Singleton s1=new Singleton(); Membership variables are privatized and cannot be called directly //Singleton s1=Singleton.s; //Singleton s2=Singleton.s; //System.out.println(s1 ==s2); Singleton s1=Singleton.getInstance(); Singleton s2=Singleton.getInstance(); System.out.println(s1 == s2); } } /*//Hungry man class Singleton{ //Private constructor, which cannot be accessed by other classes private Singleton(){} //create a class object private static Singleton s= new Singleton(); //Providing public access to the outside world public static Singleton getInstance(){ //Get examples return s; } }*/ //Slacker type,Delayed Loading Mode for Singletons class Singleton{ //Private constructor, which cannot be accessed by other classes private Singleton(){} //create a class object private static Singleton s= new Singleton(); //Providing public access to the outside world public static Singleton getInstance(){ //Get examples if (s==null) { s =new Singleton(); } return s; } }