The singleton pattern

The purpose of the singleton pattern is to ensure that only one instance of a specific class can be created [GHJ95]. In the case where an instance is created from a class defined using the singleton pattern, all other objects of the system that need to dialog with it will refer to the same instance.

Often there are cases that only one instance of a class need to be created. This is common in cases when a class needs to control and coordinate the behavior of other classes. As an example, when designing a crop simulation model, it is important to make sure that only one instance of the Simulator class is created. This is because of the particular role the Simulator class plays in the simulation process. The Simulator is responsible for creating objects that are involved in the simulation process and controls the time and the messages that objects send to each other. In the case where the user can accidentally create more than one instance of the Simulator, unexpected results could be obtained. To better understand the kind of problems that may occur when more than one instance of the Simulator is created, let us consider a simple example. Let us suppose that a simulator object is created initially and this object creates all other needed objects and establishes the relationships between them. The objects needed in the simulation process are of type Soil, Plant, and Weather. Suppose that at some point, another simulator object is created. The second simulator will have to create other objects of type Soil, Plant and Weather. As a result of having several objects of type Soil, it is not clear which object Soil is used at a time. Soil objects may be in different states and therefore, holding different values for the same attribute. Therefore, it is important to make sure that only one instance of object simulator is created. Figure 7-7 shows an example of singleton pattern.


^instance : Simulator

^getlnstanceQ : Simulator

Figure 7-7. Example of implementation of the singleton pattern.

The key to designing a singleton is to not allow users to create more than one instance of the class. Therefore, the attribute instance that references the unique instance of the class Simulator is defined as private, meaning that this attribute cannot be accessed from outside the class Simulator. A method, referred to as getlnstanceQ, returns the value of the unique instance. Figure 78 shows the Java implementation of the singleton pattern.

1 package SingletonPattern;

0 0

Post a comment