Decorator pattern gives us flexibility to extend the behavior of certain objects at runtime. This can be seperate than the existing instances of the same class. To be able to achieve Decorator pattern, we need to create certain infrastructure for it.
Page Contents [hide]
Design time consideration:
- Create a Subclass of the main class, also called a component, as a Decorator class.
- In decorator class, create an attribute with
TYPE REF TO
main class - Create
CONSTRUCTOR
in the decorator class with importing parameter REF TO Decorator class. Set the attribute from this parameter. - Redefine all other methods in decorator class inherited from Main Class. Just call the same method using the reference of the main class.
- Create subclass of decorator when a new behaviour is required. Redefine the methods for which we need different behaviour.
UML
Let’s see the UML the example:
We have a main class
OUTPUT
. We have base behavior as ALV output class ALVOUTPUT
. This behavior will execute all the time. Now, we’ll add the decorator to it as per the design time consideration steps.
Decorator class
OPDECORATOR
with attribute O_DECORATOR
with TYPE REF TO OUTPUT
. In theCONSTRUCTOR
, we have the importing parameter IO_DECORATOR
. This will set up the link between the sub behavior. Method PROCESS_OUTPUT
is redefined to call the method from the O_DECORATOR
.
We have three different additional behavior – output in PDF, Email and Excel. This is being achieved by subclassing of the decorator and redefining the
PROCESS_OUTPUT
method. Along with redefintion we’ll also call the SUPER->PROCESS_OUTPUT( )
to call the previous object’s method in the chain. Actual generation of PDF, Email and Excel is out of scope for this article.Code Lines
Lets see the code:
Run-time explanation
At runtime, we instantiate the object and we pass the previous object as reference. Thus we create the chain. Like when we instantiate the object for PDF, we pass the reference of the base behavior ALV. When we instantiate the object for Email, we’ll pass the object of PDF and so on and so forth. The chain of object would be something similar to this.
When we call the method process_ouput( ) of the LO_DECORATOR class as per the example, it would access each of the object in sequence and start processing from the last object in the chain and start processing in reverse as shown:
No comments:
Post a Comment