Continue to design patterns, this pattern should be very frequent ah, but also relatively simple, if you can not write a paper pen handy, you have to refuel AH ~
The direct introduction of several thread-safe and I think it is quite good way:
1, is not known as a bad Han, is the class loaded on the initialization of
Package Com.zhy.pattern.singlton; Public class singleton{ privatestaticnew Singleton (); Public Static Singleton getinstance () { return instance; }}
2, lazy, I like this, need double judgment
Package Com.zhy.pattern.singlton; Public classsingleton02{Private StaticSINGLETON02 instance; Public StaticSingleton02 getinstance () {if(Instance = =NULL) {synchronized (Singleton02.class) { if(Instance = =NULL) {instance=NewSingleton02 (); } } } returninstance; }}
3, the use of Java enumeration, or very recommended, simple with God horse, if not familiar with the enumeration, little Google
Public enum singleton03{ INSTANCE;}
4, the use of a holding class, mainly to not be loaded at the time of initialization
package Com.zhy.pattern.singlton; public class singleton04{ static final class Instanceholder { /span>private new Singleton04 (); public static Singleton04 getinstance () { return I Nstanceholder.instance; }}
OK, so much more, the above 4 kinds are more recommended to use, in addition to the first class loading time initialization, the other 3 is not, and 4 are guaranteed thread safety, special cases (in addition to multiple class loaders, and you do not have to use reflection and other means to generate multiple objects) is not considered.
Design Pattern Singleton mode