Java Design Pattern _ singleton mode

Source: Internet
Author: User

A hungry man single case design mode
1 /**2 * A hungry man single case design mode:3 * 1. Privatization of the constructor function. 4 * 2. Declare a reference type variable of this class, and use that variable to point to this class of object. 5 * 3. Provides a public static method for obtaining objects of this class. 6  */7 8 //a hungry man single-case design mode----> guarantee only one object in memory. 9 classsingle{Ten  One     //declare a reference type variable of this class, and use that variable to point to the class object A     private staticSingles=NewSingle (); -  -     //Privatization Constructors the     PrivateSingle () {} -  -     //provides a public static way to get objects of this class -     Public StaticSingle getinstance () { +         return s; -     } +}
Lazy Single case design mode
1 /**2 * Lazy Single case design mode:3 * 1. Privatization of the constructor function. 4 * 2. Declare a reference type variable for this class, but do not create an object. 5 * 3. Provide a public static method to obtain the object of this class, get the first to determine whether the class object has been created, if it has been created, then directly return to the object,
6 * If not yet created, the object of this class is created first and then returned.
7 */8 9 //Lazy One-case design mode----> Guarantee single is only one object in memory. Ten classsingle{ One A //declares a reference type variable of this class and does not create objects of this class - private staticsingle s; - the //privatized the constructor - PrivateSingle () {} - - //declares a public static method to get objects of this class + Public StaticSingle getinstance () { - if(s==NULL){ + synchronized(Single.class) { A if(s==NULL){ at s=NewSingle (); - } - } - } - return s; - } in}

Java Design Pattern _ singleton mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.