Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 350 – Software Design Singleton – Chapter 21

Similar presentations


Presentation on theme: "CS 350 – Software Design Singleton – Chapter 21"— Presentation transcript:

1 CS 350 – Software Design Singleton – Chapter 21
How do you ensure that only a single instance of a class is instantiated? Use the Singleton Pattern. Gang of Four Definition: Ensure a class has one instance, and provide a global point of access to it. By using a special method to instantiate the object, the method can check to see if it is already instantiated. If it is, it returns a reference to the previously instantiated object. If it is not, then the method instantiates the object and returns a reference to it. This requires that the only way to instantiate the object is through this method. Therefore, the constructor to the class must be private or protected. The goal of the Singleton is not to create a new object to keep track of what has been instantiated. Instead, the objects themselves should keep track of themselves. Importantly, client objects should not need to be concerned with whether it already exists.

2 CS 350 – Software Design Singleton – Chapter 21
Code for a Singleton public class USTax extends Tax { private static USTax instance; private USTax(); public static USTax getInstance() { if (instance == null) instance = new USTax(); return instance; }

3 CS 350 – Software Design Singleton – Chapter 21
The Singleton Pattern: Key Features Intent: You want to have only one of an object, but there is no global object that controls the instantiation of this object. You also want to ensure that all entities are using the same instance of this object, without passing a reference to all of them. Problem: Several different client objects need to refer to the same thing, and you want to ensure that you do not have more than one of them. Solutions: Guarantees one instance. Implementation: Add a private static member of the class that refers to the desired object. (Initially, it is null) Add a public static method that instantiates this class if this member is null (and sets this member’s value) and then returns the value of this member. Set the constructor’s status to protected or private so that no one can directly instantiate this class and bypass the static constructor mechanism.


Download ppt "CS 350 – Software Design Singleton – Chapter 21"

Similar presentations


Ads by Google