Packagecom.btp.t2;/** Design Patterns: A large number of practical summary and theoretical optimization of the code structure, programming style and problem-solving * way of thinking * 23 Design Patterns * * Single-case design mode: * 1. WORKAROUND: Make a class capable of creating only one object * 2. Step: ① privatize the constructor, making the class External cannot call this constructor *② creates an instance of a class inside a class *③ privatize this object, calling *④ this common method through a public method, which can only be modulated by the class, so set to static, and the instance of the class inst Ance * must also be static * * * *. A hungry man: regardless of use, the object has been created: private static Singleton instance=new Singleton (); * * Lazy Type: When using the object to create, do not create: private static Singleton1 instance=null; * Instance=new Singleton1 (); */ Public classTestsingleton { Public Static voidMain (string[] args) {//a hungry man type /*Singleton s1=singleton.getinstance (); Singleton s2=singleton.getinstance (); System.out.println (S1 = = s2);//true*/ //Lazy TypeSingleton1 s3=singleton1.getinstance (); Singleton1 S4=singleton1.getinstance (); System.out.println (S3= = S4);//true, because there is only one object, all references point to the same piece of heap memory }}//only a single instance can be created//a hungry man: When a class is created, a static object is created for use by the system and is not changed in the future, so it is inherently thread-safe. classsingleton{//1. Privatization of the constructor so that the constructor cannot be called outside of the class PrivateSingleton () {}//2. Creating an instance of a class inside a class Private StaticSingleton instance=NewSingleton (); //3. Privatization of this object, using public methods to invoke//4. This public method can only be adjusted by the class, so it is set to static, and the instance of the class instance must also be static Public StaticSingleton getinstance () {returninstance; }}//lazy: There may be a thread-safety issueclasssingleton1{//1. Privatization of Constructors PrivateSingleton1 () {}//2. Declaring a Private object Private StaticSingleton1 instance=NULL; //3. Create a method that calls the private object of this class, and call this method to actually create the object Public StaticSingleton1 getinstance () {if(Instance = =NULL) {instance=NewSingleton1 (); } returninstance; } }
javase-single-Case model beginner