Recently, we have seen how we can achieve OO Design Pattern Decorator in ABAP using the inheritance tree. Achieving decorator seems to be little bit complex, but it gets easier as we get used with it.
Problem
As you can notice, in this example that we had to use the helper variable LO_PRE to retain the object reference of the previous instantiated object.
Decorator using Helper
DATA: lo_decorator TYPE REF TO output,
lo_pre TYPE REF TO output. ” Helper Variable
lo_pre TYPE REF TO output. ” Helper Variable
* Setup objects
* standarad object
CREATE OBJECT lo_decorator TYPE alvoutput.
lo_pre = lo_decorator.
* standarad object
CREATE OBJECT lo_decorator TYPE alvoutput.
lo_pre = lo_decorator.
* testing Decorator
IF iv_pdf IS NOT INITIAL.
CREATE OBJECT lo_decorator TYPE op_pdf
EXPORTING
io_decorator = lo_pre.
lo_pre = lo_decorator. ” << ENDIF. IF iv_email IS NOT INITIAL. CREATE OBJECT lo_decorator TYPE op_email EXPORTING io_decorator = lo_pre. lo_pre = lo_decorator. " << ENDIF. [/abap_code] If we don't use the helper variable and do the code like this - it seems fine - but it goes to endless loop. [abap_code slider="X" title="Without using Helper variable"] CREATE OBJECT: lo_decorator TYPE alvoutput lo_decorator TYPE op_pdf EXPORTING io_decorator = lo_decorator, lo_decorator TYPE op_emain EXPORTING io_decorator = lo_decorator. [/abap_code]
IF iv_pdf IS NOT INITIAL.
CREATE OBJECT lo_decorator TYPE op_pdf
EXPORTING
io_decorator = lo_pre.
lo_pre = lo_decorator. ” << ENDIF. IF iv_email IS NOT INITIAL. CREATE OBJECT lo_decorator TYPE op_email EXPORTING io_decorator = lo_pre. lo_pre = lo_decorator. " << ENDIF. [/abap_code] If we don't use the helper variable and do the code like this - it seems fine - but it goes to endless loop. [abap_code slider="X" title="Without using Helper variable"] CREATE OBJECT: lo_decorator TYPE alvoutput lo_decorator TYPE op_pdf EXPORTING io_decorator = lo_decorator, lo_decorator TYPE op_emain EXPORTING io_decorator = lo_decorator. [/abap_code]
Why this happens
The endless loop is the result of the usage of LO_DECORATOR. Because when system executes this statement it carries the new object created in the IO_DECORATOR parameter. So, the object has the reference of its OWN object instead of the SUPER object. This happens because as soon as system executes the statement CREATE OBJECT it creates the object before calling the constructor. SO, when it reaches to constructor it has its OWN object reference instead of the SUPER object reference.
This is what SAP Help point out to:
The CREATE OBJECT statement creates an instance of a class or object and assigns the object reference to the reference variable oref. Directly after the object has been created, the instance constructor of the class is executed.
Original forum discussion can be found on SDN at Design Pattern, The decorator
No comments:
Post a Comment