A Singleton class is a design pattern that restricts the instantiation of a class to one single object throughout the lifecycle of a program. This is useful when exactly one object is needed to coordinate actions across the system — such as logging, configuration management, or connection handling.
Key Characteristics of Singleton Pattern:
- Only one instance of the class exists.
- The class controls its own instantiation.
- A global access point is provided to access.
*&---------------------------------------------------------------------*
*& Report ZREP_LCLCLASS
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT zrep_lclclass.
CLASS lcl_class_singleton DEFINITION CREATE PRIVATE.
PUBLIC SECTION.
" to check the instance is created or not.
CLASS-METHODS: m_factory RETURNING VALUE(r_instance) TYPE REF TO lcl_class_singleton.
" getter and setter methods
METHODS : get_attribute RETURNING VALUE(r_attribute) TYPE i,
set_attribute IMPORTING m_attribute TYPE i.
PRIVATE SECTION.
* CLASS-DATA: obj_instance TYPE REF TO lcl_class_singleton.
DATA gv_attribute TYPE i.
ENDCLASS.
class lcl_class_singleton IMPLEMENTATION.
method m_factory.
if r_instance is not BOUND.
r_instance = new lcl_class_singleton( ).
endif.
ENDMETHOD.
method get_attribute.
r_Attribute = gv_Attribute.
ENDMETHOD.
method set_attribute.
gv_Attribute = m_attribute.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
" create an instance of class
data(lo_obj) = lcl_class_singleton=>m_factory( ).
" set the value for the attribute.
lo_obj->set_attribute( 10 ).
" try to create another instace of the class.
data(lo_obj2) = lcl_class_singleton=>m_factory( ).
" check the attribute of the new instance
" it should be same as go_obj as it contains a static attribute
" get the data and print it.
write: 'First object attribute value ', lo_obj->get_attribute( ).
write :/ 'Second object attribute value ', lo_obj2->get_attribute( ).
Output: