Java 17 Recipes


-3. Creating a Class with a Single Instance


Download 3.2 Mb.
Pdf ko'rish
bet93/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   89   90   91   92   93   94   95   96   ...   245
Bog'liq
Java 17 Recipes

5-3. Creating a Class with a Single Instance
 Problem
You want to create a class for which only one instance can exist in the entire application 
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 
instance. Suppose that you wanted to create a Statistics class that would calculate 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 to prevent multiple instances from being generated. The 
following class represents the singleton pattern.
package org.java17recipes.chapter05.recipe05_03;
import java.util.ArrayList;
import java.util.List;
Chapter 5 ObjeCt-Oriented java


155
import java.io.Serializable;
public class Statistics implements Serializable {
private static final long serialVersionUID = 1L;
// Definition for the class instance
private static final 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(){
}
/**
* Accessor for the statistics class. Only allows for one instance of the
* class to be created.
* @return
*/
public static Statistics getInstance(){
return INSTANCE ;
}
/**
* @return the teams
*/
public List getTeams() {
return teams;
}
/**
* @param teams the teams to set
*/
public void setTeams(List teams) {
this.teams = teams;
}
}
Chapter 5 ObjeCt-Oriented java


156
If another class attempts to create an instance of this class, it uses the getInstance() 
accessor method to obtain the singleton instance. It is important to note that the 
solution code demonstrates eager instantiation, which means that the instance is 
instantiated when the singleton is loaded. For lazy instantiation, which is instantiated on 
the first request, you must take care to synchronize the getInstance() method to make 
it thread-safe. The following code demonstrates an example of lazy instantiation.
public static Statistics getInstance(){
synchronized(Statistics.class){
if (instance == null){
instance = new Statistics();
}
}
return instance;
}

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   89   90   91   92   93   94   95   96   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling