Thursday, 21 May 2020

Singleton Example

CLASS lcl_singlton DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS : get_instance RETURNING VALUE(ex_singleton) TYPE REF TO lcl_singlton.
    METHODS :
      set_text IMPORTING im_text TYPE char100,
      write_details.

  PRIVATE SECTION.
    CLASS-DATA : lo_singleton TYPE REF TO lcl_singlton.
    DATA : text TYPE char100.
ENDCLASS.

CLASS lcl_singlton IMPLEMENTATION.
  METHOD get_instance.
    IF lo_singleton IS INITIAL.
      lo_singleton = NEW lcl_singlton( ).
    ENDIF.
    ex_singleton = lo_singleton.
  ENDMETHOD.
  METHOD set_text.
    text = im_text.
  ENDMETHOD.
  METHOD write_details.
    WRITE :/ text.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.

Data : lo_singleton1 type REF TO lcl_singlton,
       lo_singleton2 type REF TO lcl_singlton.

Write :/ 'From first object'.
lo_singleton1 = lcl_singlton=>get_instance( ).
lo_singleton1->set_text( im_text = 'test singleton' ).
lo_singleton1->write_details( ).
Write :/ 'From Second object'.
lo_singleton2 = lcl_singlton=>get_instance( ).
lo_singleton2->write_details( ).

2 comments: