SAP ABAP Advanced Cookbook
上QQ阅读APP看书,第一时间看更新

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:

  1. Make sure the CREATE PRIVATE addition is included in the singleton class definition.
  2. Within the definition, a static attribute number_of_instances having type integer is added to the private section.
    How to do it...
  3. The implementation of the class is then written. The factory method has to be slightly modified in order to force the singleton characteristic.
    How to do it...
  4. In the implementation of the 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.
    How to do it...

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.

How it works...