Friday, March 31, 2017

Guess the output : OO ABAP Singleton Class Sample Code



Singleton Class Example


*&---------------------------------------------------------------------*
*& Report YTEST_OOABAP4
*&
*&---------------------------------------------------------------------*
*&class <name> definition create private.
*&class-data instance type ref to <name> in private section
*&Class_method changing reference type ref to <name> in Public section
*&
*& By Debesh
*&---------------------------------------------------------------------*

REPORT ytest_ooabap4.

DATA : it_mara TYPE TABLE OF mara,
wa_mara TYPE mara.
*----------------------------------------------------------------------*
* CLASS CL_SINGLETON DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_singleton DEFINITION CREATE PRIVATE. "create a private class
PUBLIC SECTION.
METHODS: get_mara. "actual method get mara
CLASS-METHODS: instantiate CHANGING lr_inst TYPE REF TO cl_singleton . "create a static method
PRIVATE SECTION.
CLASS-DATA: lr_inst TYPE REF TO cl_singleton. "private variable
ENDCLASS. "CL_SINGLETON DEFINITION

*----------------------------------------------------------------------*
* CLASS CL_SINGLETON IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_singleton IMPLEMENTATION.
METHOD get_mara.
SELECT * FROM mara INTO TABLE it_mara UP TO 5 ROWS.
LOOP AT it_mara INTO wa_mara.
WRITE:/ wa_mara-matnr, wa_mara-mtart, wa_mara-meins, wa_mara-matkl.
ENDLOOP.
ENDMETHOD. "GET_MARA
METHOD instantiate.
IF lr_inst IS INITIAL.
CREATE OBJECT lr_inst. "create object
ELSE.
ULINE.
WRITE : 'Already instantiated'.
ENDIF.
ENDMETHOD. "INSTANTIATE

ENDCLASS. "CL_SINGLETON IMPLEMENTATION

START-OF-SELECTION.

DATA : lo_class TYPE REF TO cl_singleton.
*CREATE OBJECT lo_class."syntax error

cl_singleton=>instantiate( CHANGING lr_inst = lo_class ). "get instance of class
*CREATE OBJECT LO_CLASS.
lo_class->get_mara( ). "get mara data

cl_singleton=>instantiate( CHANGING lr_inst = lo_class ).





OUTPUT



Test Program




38 DATA KWH
41 DATA KWH
43 DATA KWH
46 DATA KWH NUISU
49 DATA KWH


Already instantiated

No comments:

Post a Comment