Transferred from: Xingoo
Single-Case mode:
The guaranteed class has only one instance and is available for global use. This class creates the object itself and provides an externally exposed method of invocation. (Construction method Private)
Usage scenarios:
When a class has only one instance and can access it from a fixed access point.
Code Show:
"A Hungry man mode"
Public classSingleton {Private Static FinalSingleton Singleton =NewSingleton (); The final variable cannot be modified herePrivateSingleton () {/*** Construction Method Privatization*/ } /** Return instance, method is static*/ Public StaticSingleton getinstance () {returnSingleton; }}
"Lazy Mode"
Public classSingleton2 {Private StaticSingleton2 Singleton =NULL; PrivateSingleton2 () {/*** Construction Method Privatization*/ } /** Synchronization method synchronized, when an instance is required, take the creation, return the instance, the method is static*/ Public Static synchronizedSingleton2 getinstance () {if(singleton==NULL) {Singleton=NewSingleton2 (); } returnSingleton; }}
"Design pattern"--Singleton mode