How Java Singleton patterns are written

Source: Internet
Author: User

Wrote a lot of single-instance pattern implementation, today paste a book in the wording.
Singleton pattern Definition: A design pattern that is used when only one instance of a class is to be created.
Requirement: There can only be one way to create an instance, and you cannot get an object reference in an uninitialized state.
Therefore, in singleton mode, you need to have a construction method that is declared private and is called only once.

 PackageOop/** * Single case Mode * * @author lunatictwo */ Public  class Singleton {    Private Final StaticSingleton instance =NewSingleton ();Private Static BooleanIsinit =false;//constructor method, only the constructor is called when initializing the instance    Private Singleton() {Super(); }Private void Init() {//Initialize method is placed in private method}//Obtain an instance by static helper method     Public Static synchronizedSingletongetinstance() {if(Isinit) {returnInstance//Determine if activation} instance.init ();//Activates the instance and saves the state as activated and does not initialize again the next time the request is createdIsinit =true;returnInstance }}

At this point, when obtaining a singleton instance, it can only be obtained by getinstance ().

How Java Singleton patterns are written

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.