A
singleton
class is a class that can have only one instance at a time. Any attempt to create a second or more instances should not be allowed. This recipe shows how to create a class based on the singleton design.
We will use the same class created in the last recipe of factory
method. We will make few changes to the class so that we can prevent the creation of multiple instances of the class. We will make a copy of the class (program) shown in the previous recipe and modify it. The name of the copy is singleton_class
.
For creating a singleton
class, follow these steps:
CREATE PRIVATE
addition is included in the singleton
class definition.number_of_instances
having type integer
is added to the private section.factory
method has to be slightly modified in order to force the singleton
characteristic.singleton
class, the factory
method now contains an IF
statement that first checks the number of instances already there when the factory
call is made. If the first instance is being created (that is, number_of_instances
equals 0), the employee object is created and number_of_instances
is set as 1
. An ELSE
condition is included to output a message if one instance already exists.Similar to the previous recipe, we try to instantiate two objects emp1
and emp2
, having number 0000012
and 00000014
respectively. However, in our singleton
class, we have added an attribute number_of_instances
, which keeps track of the number of class instances that already exist. Upon creation of the first object, the factory
method increments this static attribute to 1
. On the second object creation attempt, the IF
statement does not allow the CREATE OBJECT
statement to be called a second time. The result is that the second object is not created. No further attempts of object creation will be allowed. Rather, a message saying that only one object instantiation is allowed is outputted for the second object creation attempt.
18.220.88.62