Creating global singleton class in OOABAP

+ -

Follow below steps to create singleton class in Object oriented ABAP

Step 1: Create a private class in Se24

Go to SE24, provide name as ZSAPN_CL_SINGLETON and click on create.

Singleton class in Object Oriented ABAP

Provide description, select class as private and save.

Singleton class in Object Oriented ABAP

Go to attributes tab, add a private attribute of type reference to same class.

Singleton class in Object Oriented ABAP

Go to methods tab, add a static method INSTANTIATE and click on parameters button .

Singleton class in Object Oriented ABAP

Add a returning parameter as below.

Go back to methods, double click on method INSTANTIATE and add below code.

  METHOD INSTANTIATE.

    IF LV_INST IS NOT BOUND.
      CREATE OBJECT RO_INST.
      LV_INST = RO_INST.
    ELSE.
      RO_INST = LV_INST.
    ENDIF.

  ENDMETHOD.

Save and activate the class, go to SE38, create a program ZSAPN_SINGLETON_GLOBAL.

Try to create instance directly.
REPORT ZSAPN_SINGLETON_GLOBAL.

DATA : LO_CLASS TYPE REF TO ZCL_SAPN_SINGLETON.

create OBJECT lo_class.
It will through an error.

Now create instance through static method.

REPORT ZSAPN_SINGLETON_GLOBAL.
DATA : LO_CLASS TYPE REF TO ZCL_SAPN_SINGLETON.
LO_CLASS = ZCL_SAPN_SINGLETON=>INSTANTIATE( ).
Now you can access all public instance components through the object.

Learner Questions


No Questions by learners, be first one to ask ..!!

    Please Sign in to ask a question

    Was this lesson helpful to you? Yes No 23 People out of 25 think this lesson helpful


    Lesson Navigation

    ←Previous Chapter
    Next Chapter →