Sometimes there is a need to instantiate an object at a time, that means only one instance is required at one point of time. This is a very common requirement while designing an application. To achieve such a scenario, there is one concept of ‘Singleton Pattern’ or ‘Singleton Class’ in OOABAP.
This was the theoretical part. Now, a question comes, that how to achieve it in real? So, here the answer is: By declaring the constructor as a ‘Private’ one. This private constructor can be created after changing the instantiation type to private. This helps us to restrict the further creation of an object of a class.
Definition of Singleton Class in ABAP:
A class is said to be a singleton class if it can have the utmost one instance only.
Following is a procedure to create a singleton class :
- Visibility of class should be private.
- Declare a private attribute with reference to the same class, in which it is being declared.
- Create a public static method with returning parameter, having a reference of the same class.
- Create an implementation and an object inside the implementation of a public static method.
- To create an instance for the singleton class, call this public static method in any program.
For the better understanding of this Singleton Concept, let’s consider this below sample program and here as you can see that object creation of a singleton class is not possible outside the class. So, this is how a singleton pattern works.
In the above program, we have implemented a local class lcl_singleton_test inside an ABAP Report. In the class definition, we have kept the class as private and have declared a Public section. Under the public section, we have declared a static attribute lo_singleton which refers to the program itself. Also, we have defined a local variable v of type integer. Then, we have defined the class constructor and a method set_name for the class.
Later, we have implemented the class where we are creating an object under class constructor. Also, we have assigned a value i.e. “GEETANSHU” to the local variable v.
Now, in the report code, we are doing a static call to our class via its object r1.
Advantages of Singleton Class in ABAP:
- With the use of Singleton class, testability improves.
- Singleton pattern supports the main moto of Object Oriented Design principle by allowing it to open for enhancements and closed for modifications.
- The advantage of using a private constructor in Singleton class (as no one create an object of your class).