A static property of a class only initializes a static variable the first time the class is loaded Lazy Style:
1 //Lazy Single-case2 Public classSingleton1 {3 //4 Define a variable to store the created class instance4 //5 to use in static methods, you need to add a static modifier5 Private StaticSingleton1 instance =NULL;6 //1 Privatization constructors, internal controls the number of instances created7 PrivateSingleton1 () {}8 //2 Define a method to provide a class instance to the client9 //3 need to define a class method, add staticTen Public StaticSingleton1 getinstance () { One //6 Determine if the variable for the stored instance has a value A if(Instance = =NULL){ - //6.1 If not, create a class instance and assign the variable to the storage class instance -Instance =NewSingleton1 (); the } - //6.2 If there is a value, use it directly - returninstance; - } + } - //without internal class processing, the main drawback of this approach is that once I have accessed any of the other static domains of Singleton1, + //will cause the initialization of the instance, and the fact is that we may not have used this instance from the beginning to the end, resulting in a waste of memory
non-synchronized lazy-type is thread insecure.
// a hungry man type single case Public class Singleton {privatestaticnew Singleton (); Private Singleton () {} Public Static Singleton getinstance () { return Singleton; }}
The a hungry man is thread-safe because the virtual machine is loaded only once and does not occur when the class is loaded.
The main drawback of this approach, which is not handled internally, is that once I access any of the other static domains of Singleton1, it causes the initialization of the instance, and the fact is that it is possible that we have not used this instance from the beginning to the end, resulting in a waste of memory.
Change to use static inner class as a singleton
Public classSingleton {//1 Privatization constructors, internal controls the number of instances created PrivateSingleton () {}//2 Defining a method to provide a class instance to the client//3 need to define a class method, add static Public StaticSingleton getintance () {returnsingletoninstace.instance; } //static inner class as an instance, a static property of a class is initialized only the first time the class is loaded Private Static classsingletoninstace{StaticSingleton instance =NewSingleton (); }}
Design mode-Singleton mode