Why do I need a single case? Only because of the one-child policy of the country (of course, 2 can now be born)
The singleton is a very lonely species, because it has only one of its classes.
The most common is the lazy and a hungry man mode,
1. Lazy, why so called, look at English, the original Lazy loading,lazy (lazy), laoding (sound like a guy), called lazy, and then a guy = = a man, for good, so lazy.
The most basic model of the lazy:
Singleton mode public class Singleton {//privatized construction method, which makes it impossible for an external instance to be generated by new; private Singleton () {}//lazy mode private static Singleton instance = null;//does not add synchronized, thread has a problem, public static Singleton getinstance () {if (instance = = null) instance = new Singleton (); Retu rn instance;}}
The above thread security issue, if multi-threaded case, can be drawn multiple instances.
After adding synchronized improvements:
//single-case mode Public classSingleton {//privatization of construction methods, making it impossible for outsiders to generate instances by using new; PrivateSingleton () {}//Lazy Mode Private StaticSingleton instance =NULL; //do not add synchronized, thread has a problem; Public Staticsynchronized Singleton getinstance () {if(Instance = =NULL) Instance=NewSingleton (); returninstance; }}
Lazy, because it is used to load.
A hungry man, Han will not explain, there is. Why is it called hungry? Because whether or not you use this singleton, it will instantiate, in memory, like a very hungry person, whatever, eat first.
Specific as follows:
A Hungry man mode public class Singleton2 {//privatized construction method, so that the appearance cannot use new to produce an instance. Private Singleton2 () {}//A hungry man mode, regardless of whether you have no use of this instance, first instantiate. Private static Singleton2 instance =new Singleton2 ();p ublic static Singleton2 getinstance () {return instance;};}
Java single-instance mode (singleton)