Java Reference
In-Depth Information
Problem
You would like to create a class for which only one instance can exist in the entire ap-
plication, so that all application users interact with the same instance of that class.
Solution 1
Create the class using the Singleton pattern. A class implementing the Singleton pattern
allows for only one instance of the class and provides a single point of access to the in-
stance. Suppose that you wanted to create a Statistics class that would be used for
calculating the statistics for each team and player within an organized sport. It does not
make sense to have multiple instances of this class within the application, so you want
to create the Statistics class as a Singleton in order to prevent multiple instances
from being generated. The following class represents the Singleton pattern:
package org.java8recipes.chapter5.recipe5_03;
import java.util.ArrayList;
import java.util.List;
import java.io.Serializable;
public class Statistics implements Serializable {
// Definition for the class instance
private static volatile Statistics instance = new
Statistics();
private List teams = new ArrayList();
/**
* Constructor has been made private so that outside
classes do not have
* access to instantiate more instances of Statistics.
*/
private Statistics(){
}
Search WWH ::




Custom Search