Java Reference
In-Depth Information
The private field can be assigned from within a static initializer block or, more simply, using
an initializer. The
getInstance()
method (which must be public) then simply returns this
instance:
public
public class
class
Singleton
Singleton
{
private
private static
static
Singleton instance
;
/** A private Constructor prevents any other class from instantiating. */
private
private
Singleton
() {
// nothing to do this time
}
/** The Static initializer constructs the instance at class loading time;
* this is to simulate a more involved construction process (it it
* were really simple, you'd just use an initializer)
*/
static
static
{
instance
=
new
new
Singleton
();
}
/** Static 'instance' method */
public
public static
static
Singleton
getInstance
() {
return
return
instance
;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public
public
String
demoMethod
() {
return
return
"demo"
;
}
}
Note that the method of using “lazy evaluation” in the
getInstance()
method (which is ad-
vocated in
Design Patterns
), is not necessary in Java because Java already uses “lazy load-
ing.” Your
Singleton
class will probably not get loaded unless its
getInstance()
is called,
so there is no point in trying to defer the singleton construction until it's needed by having
getInstance()
test the singleton variable for null and creating the singleton there.
Using this class is equally simple: simply get and retain the reference, and invoke methods
on it: