Welcome, you seems to be new here. Get Connected: Become a Fan on Facebook Join ABAP Help on Google+ Subscribe to email X

OO Design Pattern Decorator – Why do we need to use helper variable?

By | December 11, 2011 | ABAP Objects, OO Design Patterns | 454 views

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
*   Setup objects
*   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.
 

If we don't use the helper variable and do the code like this - it seems fine - but it goes to endless loop.

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.
 

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.

Advertisement

Original forum discussion can be found on SDN at Design Pattern, The decorator

Further Reading

Explore all other Design patterns. More are comming soon.

Get your Social On!

Stay Tuned with ABAP Help

TAGS


Wanna say something?





=

To post ABAP code use shortcode [abap_code slider="X" title=""][/abap_code]