Hi Folks,
i am hacking on an ALV oo program and needed or wanted to implement the singleton pattern.
A singleton is a class of which only one instance exists and some means is create to access the only instance without making it global of course...
Think of it as a global variable hidden behind a puzzling coding interface. At the very end it is just a single global instance of a class, but far more cool and good looking :-)
Apart from jokes it makes sense. Obviously not in 10 lines programs. But in complex applications having a global in the scope of a whole project can be problematic... the singleton can be anice way to control this "global" and access it in a discplined and controlled manner
In my case i have program that runs on one person. So my "app" object is bound to the person and there is only one throuout the processing.
So i need a means to have a central object instance which can be accessed by all classes that need it.
In abap it can be done like in the following coding.
The class-method is a method that is run per "class" and not per "object" ( the instance of the class)
The class constructor is run only once per program before the class is called for the first time.
So the class construcor instantiates the object ( the only existing instance )
The class method gives access just to this one and only existing oblect of the given singleton class.
So in my program i can call it like this
...
DATA lr_my_app TYPE REF TO zcl_my_app.
lr_my_app = zcl_my_app=>get_singleton( ).
CALL METHOD gr_my_app->init
....
Here the class example.
CLASS zcl_my_app DEFINITION.
PUBLIC SECTION.
class-METHODS: class_constructor.
METHODS: init .
CLASS-METHODS: get_ref RETURNING value(r_ref) TYPE REF TO zcl_my_app.
PRIVATE SECTION.
CLASS-DATA ar_singleton TYPE REF TO zcl_my_app.
CLASS zcl_my_app IMPLEMENTATION.
METHOD: class_constructor.
CREATE OBJECT ar_singleton.
ENDMETHOD. "constructor
METHOD: init.
*Do whatever
ENDMETHOD. "init
METHOD: get_ref.
r_ref = ar_singleton.
ENDMETHOD. "get_ref
One last word: i have seen implementations in the internet like this:
method GET_OBJECT. " returning value(R_OBJECT) type ref to ZCL_blabla . * if zcl_blabla=>r_singleton is not bound. create object zcl_blabla=>r_singleton. endif. * r_object = zcl_sblabla=>r_singleton . endmethod.
Can i say that it is the same but at the same time it really sucks :-) LOL ?