1 PackageCom.study.mode;2 /**3 * Singleton mode: Lazy type, when needed to create. 4 * @ClassName: SingleBean25 * @authorBluelake6 * @date September 5, 2012 PM 9:08:217 */8 Public classSingleBean2 {9 Ten //1. Privatization of construction methods. One PrivateSingleBean2 () { A - } - //2. Create a static property of the current class the Private StaticSingleBean2 single =NULL; - - //3.1 Create an object when needed. - Public StaticSingleBean2 Getsinglea () { + if(single==NULL){ -Single =NewSingleBean2 (); + } A returnSingle ; at } - - //3.2 Because the 3.1 method thread is unsafe, there are multiple SingleBean2 instances when multi-threading. So locking - Public synchronized StaticSingleBean2 Getsingleb () { - if(single==NULL){ -Single =NewSingleBean2 (); in } - returnSingle ; to } + - //3.3, because each call 3.2 this method to lock, if there is a direct return to it, so waste memory the Public StaticSingleBean2 Getsinglec () { * //if present, return directly, there is no lock $ if(single==NULL){Panax Notoginseng //If, does not exist, locks, creates - synchronized(SingleBean2.class){ the //Robustness considerations, before creation, to judge + if(single==NULL){ ASingle =NewSingleBean2 (); the } + } - } $ returnSingle ; $ } -}
Java Singleton mode "two" lazy type