Creating classes based on singleton design pattern
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.
Getting ready
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.
How to do it...
For creating a singleton class, follow these steps:
Make sure the
CREATE PRIVATEaddition is included in thesingletonclass definition.Within the definition, a static attribute
number_of_instanceshaving typeintegeris added to the private section.
The implementation of the class is then written. The
factorymethod has to be slightly modified in order to force thesingletoncharacteristic.
In the implementation of the
singletonclass, thefactorymethod now contains anIFstatement that first checks the number of instances already there when thefactorycall is made. If the first instance is being created (that is,number_of_instancesequals 0), the employee object is created andnumber_of_instancesis set as1. AnELSEcondition is included to output a message if one instance already exists.
How it works...
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.
