Design mode-Singleton mode (Java)

Source: Internet
Author: User

One: Lazy type

1: Thread-safe double lock check mechanism

public class singleton{

Private Singleton () {}//privately constructed function, guaranteed not to be instantiated by the outside world (regardless of reflection)

private static Singlecton single = NULL;

public static Singlecton getinstance ()

{if (singleton = = null)

{

Synchronized (Singleton.class)

{if (singleton = = null)

Singleton = new Singleton ();

}

}

Return Singleton

}

}

2: Static inner class: thread safe, no lock

public class Singleton {

private Static Class lazyholder{

private static final Singleton INSTANCE = new Singleton ();

}

Private Singlecton () {}

public static final Singlecton getinstance ()

{

return lazyholder.instsnce;

}

}

Here's a summary of the static inner classes:

A: A static inner class that can access only static members of an external class.

B: Static inner classes can be instantiated

C: Static inner classes are generated as the class loads (static members are generated when the class loads)

Two: A Hungry man type:

public class singleton{

Private Singlecton () {}

Pribate static final Singlecton single = new Singleton ();

public static Singlecton getinstance ()

{

return single;

}

}

Design mode-Singleton mode (Java)

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.