Singleton Pattern In OOPS ABAP
Singleton design patterns in ABAP is used in cases where we do not want multiple instantiation of an object.
A singleton design pattern should follow the below rules
- Singleton class should be private
- There should be a private attribute with reference to the singleton class.
- There has to be public static method with returning parameter referring to the singleton class.
- Create object in the implementation of the above public static method with returning parameter as the object of the class and return the object of the class
Now the only way of creating the instance of the class in your program is to call the public static method.
Throughout your program it is not possible to create another instance as it is a singleton pattern.
See the below example
*&---------------------------------------------------------------------*
*& Report ZSINGLETON
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT zsingleton.
CLASS lcl_object_class DEFINITION CREATE PRIVATE.
PUBLIC SECTION.
CLASS-DATA: lo_instance TYPE REF TO lcl_object_class READ-ONLY.
DATA: x TYPE i.
CLASS-METHODS: get_instance returning VALUE(ro_instance) TYPE REF TO lcl_object_class.
METHODS: set_value .
ENDCLASS.
CLASS lcl_object_class IMPLEMENTATION.
METHOD get_instance.
if lo_instance is NOT BOUND.
CREATE OBJECT lo_instance.
ENDIF.
ro_instance = lo_instance.
ENDMETHOD.
METHOD set_value.
x = x + 1.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA: obj TYPE REF TO lcl_object_class.
DATA: obj1 TYPE REF TO lcl_object_class.
DATA: y TYPE i.
obj = lcl_object_class=>get_instance( ). " getting instance of the singleton class for the 1st time
obj->set_value( ).
y = obj->x.
WRITE:/ y .
obj1 = lcl_object_class=>get_instance( ). " getting instance of the singleton class second time
obj1->set_value( ).
y = obj1->x.
WRITE:/ y .

Follow My Blog
Get new content delivered directly to your inbox.