Java Singleton Mode

Source: Internet
Author: User

Java Singleton Mode

I have written many Singleton implementations, And I am posting a book today.
Singleton mode is defined as a design mode, which is used when you only need to create an instance for the class.
Requirement: You can only create an instance in one way, and cannot get an object reference in the uninitialized state.
Therefore, in singleton mode, a constructor declared as private must be called only once.

Package oop;/*** Singleton mode ** @ author lunatictwo */public class Singleton {private final static Singleton instance = new Singleton (); private static boolean isInit = false; // constructor. The constructor private Singleton () {super ();} private void init () is called only when the instance is initialized () {// put the initialization method in the private method} // obtain the public static synchronized Singleton getInstance () {if (isInit) {return instance through the static auxiliary method; // determine whether the instance is activated} instance. init (); // activate the instance and save the status as activated. isInit = true; return instance;} will not be initialized again the next time the instance is created ;}}

In this case, you can only get the instance by getInstance.

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.