Hello,

Sign up to join our community!

Welcome Back,

Please sign in to your account!

Forgot Password,

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask a question.

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

SAP EWM Help Latest Questions

  • 0
  • 0
DPM125

What is Singleton Class ? how to use Singleton class in SAP ABAP ?

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-METHODSm_factory RETURNING VALUE(r_instanceTYPE REF TO lcl_class_singleton.
  " getter and setter methods
    METHODS get_attribute RETURNING VALUE(r_attributeTYPE 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_attribute10 ).

   " try to create another instace of the class.
    data(lo_obj2lcl_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:

Related Questions

Leave an answer

Leave an answer