Singleton design Pattern: The construction method is privatized, the static property and method are defined inside the class, and the static method is used to get the instantiated object of this class; no matter how many instanced objects are generated externally, there is essentially only one instanced object
A hungry man single-case design
classsingleton{Private Static FinalSingleton INSTANCE =NewSingleton ();//produces an instantiated object PrivateSingleton () {}//Encapsulation Construction Method Public StaticSingleton getinstance () {returnINSTANCE;//get instantiated Object } Public voidprint () {System.out.print ("Hello word"); }} Public classtest{ Public Static voidMain (String args[]) {Singleton s= Singleton.getinstance ();//regardless of how many times the getinstance () method is called, the resulting instantiation object is the sameS.print (); }}
Lazy Style design mode
classsingleton{Private Static FinalSingleton INSTANCE;//defines an object of this class that is not instantiated PrivateSingleton () {}//Encapsulation Construction Method Public StaticSingleton getinstance () {if(INSTANCE = =NULL) {INSTANCE=NewSingleton (); } returnINSTANCE;//get instantiated Object } Public voidprint () {System.out.print ("Hello word"); }} Public classtest{ Public Static voidMain (String args[]) {Singleton s= Singleton.getinstance ();//regardless of how many times the getinstance () method is called, the resulting instantiation object is the sameS.print (); }}
Multiple design Patterns: privatization of construction methods, resulting in a specific number of objects
classsex{PrivateString sex; Private Static FinalSex man =NewSex ("Male"); Private Static FinalSex WOMAN =NewSex ("female"); Privatesex (String sex) { This. Sex =sex; } Public StaticSex getinstance (intch) { Switch(CH) { Case1: returnMan ; Case2: returnWOMAN; default: return NULL; } } PublicString toString () {returnsex; }} Public classtest{ Public Static voidMain (String args[]) {Sex s= Sex.getinstance (1); System.out.println (s); }}
A single-instance design pattern and multiple design patterns for Java design patterns