Java Reference
In-Depth Information
Note There is a test class within the recipe5_03 package that you can use to
work with the enum Singleton solution.
How It Works
The Singleton pattern is used to create classes that cannot be instantiated by any other
class. This can be useful when you only want one instance of a class to be used for the
entire application. The Singleton pattern can be applied to a class by following three
steps. First, make the constructor of the class private so that no outside class can in-
stantiate it. Next, define a private static volatile field that will represent an
instance of the class. The volatile keyword guarantees each thread uses the same
instance. Create an instance of the class and assign it to the field. In the solution to this
recipe, the class name is Statistics , and the field definition is as follows:
private static volatile Statistics instance = new
Statistics();
Last, implement an accessor method called getInstance() that simply returns
the instance field. The following code demonstrates such an accessor method:
public static Statistics getInstance(){
return instance;
}
To use the Singleton from another class, call the Singleton's getInstance()
method. This will return an instance of the class. The following code shows an ex-
ample of another class obtaining an instance to the Statistics Singleton that was
defined in solution 1 to this recipe.
Statistics statistics = Statistics.getInstance();
List teams = statistics.getTeams();
Any class that calls the getInstance() method of the class will obtain the
same instance. Therefore, the fields contained within the Singleton have the same value
for every call to getInstance() within the entire application.
Search WWH ::




Custom Search