Design Pattern Singleton mode

Source: Internet
Author: User

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

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.