Java 17 Recipes
-3. Creating a Class with a Single Instance
Download 3.2 Mb. Pdf ko'rish
|
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 /** * 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 return teams; } /** * @param teams the teams to set */ public void setTeams(List 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: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling