Singleton design Pattern : guarantees that a class has only one instance and provides a global access point to access it.
1. Privatization of construction methods
2. Declare an object of this class
3, to provide a static method to obtain an object instance
When do I use it?
1, through the use of tools in the design of the class;
2, when there is no attribute in a class;
3. This class is used very frequently as a tool class.
Two different ways:
One, a hungry man type
1 PackagePractice1;2 //single-case mode3 Public classTest7 {4 Public Static voidMain (string[] args) {5Singleton s=singleton.getinstance ();6 S.method ();7 }8 }9 classsingleton{Ten Private StaticSingleton singleton=NewSingleton ();//Create objects when defined One PrivateSingleton () {//Structuring Method Privatization A } - Public StaticSingleton getinstance () {//provides a global access point to the external, static method - returnSingleton; the } - Public voidMethod () {//test Method -System.out.println ("Method"); - } +}
A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is thread-safe.
Second, lazy-type
classsingleton2{Private StaticSingleton2 singleton2=NULL; //not directly created when defining PrivateSingleton2 () {}//Structuring Method Privatization Public StaticSingleton2 getinstance () {if(singleton2==NULL) {Singleton2=NewSingleton2 (); } returnSingleton2; } Public voidMethod () {//test MethodSystem.out.println ("Method"); }}
java-Single case design mode