Java implements various types of singleton patterns

Source: Internet
Author: User

Single example is the simplest design mode, the use of self-needless to say, but write a simple case is also a test of a procedural ape foundation, which is why many interviewers are happy to let the interviewer write a single case, is so-called simple and not simple. Needless to say, the following Java to implement a variety of single-case bar.
1. A Hungry man mode

publicclass Singleton{  privatestaticnew Singleton();  privateSingleton(){}  publicstaticgetInstance(){    return instance;  }}

2. Lazy mode

publicclass Singleton{  privatestatic Singleton instance;  privateSingleton(){}  publicstaticgetInstance(){    ifnull){      new Singleton();      return instance;    }       return instance;  }}

3. Thread-Safe single-case mode

publicclass Singleton{  privatestatic Singleton instance;  privateSingleton(){}  publicstaticgetInstance(){    ifnull){      new Singleton();      return instance;    }    return instance;  }}

4. Double-checked thread-safe single-case mode

publicclass Singleton{  privatestatic Singleton instance;  privateSingleton(){}  publicstaticgetInstance(){    ifnull){      synchronized{        ifnull){          new Singleton();          return instance;        }      }    }    return instance;  }}

5. The best thread-safe notation

publicclass Singleton{  privateSingleton(){}  privateclass SingletonHolder{    privatestaticnew Singleton();    publicstaticgetInstance(){      return instance;    }  }  publicstaticgetInstance(){    return SingletonHolder.getInstance();  }}

Java implements various types of singleton patterns

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.