1 PackageCOM.HANQI.Z1P1;2 3 //Singleton mode: Single Instance4 Public classTest0521 {5 6 //implementation, only one instance is generated in memory7 8 //Save resources and security9 Ten //implementation steps: One //1. Hide the construction method, do not allow direct new A //turn the construction method into private - PrivateTest0521 () - { the - } - - //3. Prepare an instance + Private StaticTest0521 tt=NewTest0521 (); - + A //2. Develop a method that can obtain a unique instance at //provides a static method that returns the prepared instance - Public StaticTest0521 instance () - { - returntt; - - in } - to Private intM=0; + - Public voidRun () the { * for(inti=0;i<10;i++) $ {Panax Notoginsengm++; - the +System.out.println ("m=" +m); A } the } + - $ $ -}
1 // Test Singleton mode 2 3 System.out.println ("T6: Single Case"); 4 Test0521 t6=test0521.instance (); 5 T6.run (); 6 System.out.println ("T7: Single Case"); 7 Test0521 t7=test0521.instance (); 8 T7.run ();
Test results:
Java Singleton mode