PackageCn.china; Public classSingle { Public Static voidMain (String[]args) {//S singles=s.getinstance ();//S singless=s.getinstance ();//System.out.println (singles==singless);Test tt=test.getinstance (); Test TTT=test.getinstance (); Tt.setnum (10); Ttt.setnum (20); System.out.println (Tt.getnum ()); System.out.println (Ttt.getnum ()); }/*** Single-Class design pattern: * The problem solved is to ensure that the object uniqueness of a class in memory * How to ensure the uniqueness of the object? * 1. Do not allow other programs to create this class object with new. * 2. Create an instance of this class in this class. * 3. Provide a way for other programs to get the object * Step: * 1, privatize the class constructor * 2, create a class object in this class by new, define a common method, and return the created object. */ }//a hungry man typeclasss{Private StaticS single=NewS (); PrivateS () {} Public StaticS getinstance () {returnSingle ; }}classtest{Private intnum; Private StaticTest t=NewTest (); PrivateTest () {} Public StaticTest getinstance () {returnT; } Public voidSetnum (intnum) { This. num=num; } Public intGetnum () {return This. Num; }}//Lazy Typeclasssingle2{//class is loaded with no objects, the object is created only when the GetInstance method is called. Private StaticSingle2 s=NULL; PrivateSingle2 () {} Public Staticsingle2 getinstance () {if(s==NULL) s=NewSingle2 (); returns; }}
java=== single-class design pattern a hungry man and lazy-type