A single-instance pattern of Java design patterns

Source: Internet
Author: User

A singleton pattern (Singleton pattern) is a very common design pattern. The core is to ensure that there is only one instance of the Singleton class in the system. There are a number of situations in the system that involve configuration data and the generation of unique sequence IDs.

Refer to the definition of "Zen in design mode":

Ensure a class have only one instance,and provide a global point of access to it. (Make sure that one class has an instance, and instantiate it yourself and provide it to the entire system.) )

The simple class diagram is as follows:

There are 8 ways to find a single case pattern by collecting and collating.

1, a hungry man (static constant)

 Public class Singleton {    privatestaticfinalnew  Singleton ();     Private Singleton () {    }    publicstatic  Singleton getinstance () {         return instance;}    }

This is a very simple way to understand. The instance of Singleton is initialized directly when the class is initialized. The instance is then obtained through the getinstance () method. There is no problem with thread synchronization. But there is also a drawback is not to achieve the effect of lazy loading.

2, a hungry man (static code block)

 Public class Singleton {    privatestatic  Singleton instance;     Static {        new  Singleton ();    }     Private Singleton () {    }    publicstatic  Singleton getinstance () {         return instance;}    }

A single-instance pattern of Java design 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.