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 final
Keyword 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?