Item 3-what is an efficient-in-a-implement a singleton pattern in Java?

Source: Internet
Author: User
Tags static class

Depending on the usage, there is several "correct" answers.

Since Java5 the best-of-the-do it's an enum:

 Public enum Foo {   INSTANCE;}
The right- Implement a Serializable Singleton  Public enum Elvis {    INSTANCE;     Private Final string[] favoritesongs =        "Hound Dog", "Heartbreak Hotel" };      Public void printfavorites () {        System.out.println (arrays.tostring (favoritesongs));}    }

Understanding: After JDK5, it is recommended to use an enumeration class to implement the singleton approach.

Pre Java5, the most simple case is:

 Public Final classFoo {Private Static FinalFoo INSTANCE =NewFoo ();//instance was instantiated when Foo was loaded    PrivateFoo () {if(INSTANCE! =NULL) {            Throw NewIllegalStateException ("Already instantiated"); }    }     Public StaticFoo getinstance () {returnINSTANCE; }}

Let's go over the code. First, you want the class to be final. In this case, I ' ve used the finalKeyword to let the users know it is final. Then you need the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create aprivate static final Foo field to hold the only instance, and A& Nbsp;public static Foo getinstance ()  method to return it. The Java specification makes sure that the constructor are only called when the class is first used.

when you have a very large object or heavy construction code and also has other accessible static methods or fields that Might be used before a instance is needed, then and only then you need to use lazy initialization.

You can use a to private static class load the instance. The code would then look like:

 Public Final classFoo {Private Static classFooloader {Private Static FinalFoo INSTANCE =NewFoo (); }    PrivateFoo () {if(Fooloader.instance! =NULL) {            Throw NewIllegalStateException ("Already instantiated"); }    }     Public StaticFoo getinstance () {returnFooloader.instance;//The Fooloader class was loaded and instantiated when the getinstance () method was called instance    }}

Since the line private static final foo INSTANCE = new Foo ();  is only executed when the class Fooloader are actually used, this takes care of T He lazy instantiation , and is it guaranteed Thread safe.

When you are also want to being able to serialize your object you need to make sure that deserialization won ' t create a copy.

 Public Final classFooImplementsSerializable {Private Static Final LongSerialversionuid = 1L; Private Static classFooloader {Private Static FinalFoo INSTANCE =NewFoo (); }    PrivateFoo () {if(Fooloader.instance! =NULL) {            Throw NewIllegalStateException ("Already instantiated"); }    }     Public StaticFoo getinstance () {returnfooloader.instance; } @SuppressWarnings ("Unused")    PrivateFoo readresolve () {returnfooloader.instance; }}

the method readresolve ()  will make sure the only instance would be returned, even When the object is serialized in a previous run of your program.

Item 3-what is an efficient-implement a singleton pattern in 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.