Factory Method design pattern could be most used design pattern in the modern world application. Factory method design pattern hides all the complexity of the instantiating an object from the consumer.
This DP provides an unique interface for object instantiation. This interface creates an object but let subclasses decide which class to instantiate.
Design time consideration:
- Create a Super Class with Factory method
- Create importing parameters: This would be used as conditions to define the subclass name
- Inherit the Subclasses from the Super class
- Define an object reference type to Super Class
UML:
For demo purpose, we will use this UML.
We have OPHANDLER which contains the FACTORY method. This method is Public and STATIC. This super class has another method called PROCESS_OUTPUT( ). We’ll also inherit some subclasses from the class OPHANDLER: OPHANDLER_ZABC to process ZABC output and OPHANDLER_ZXYZ to process ZXYZ output.
The FACTORY method has one importing parameter: Output Type and one Returning parameter, the object. Based on the requested output type, we’ll instantiate the object. For demo, I kept the implementation of FACTORY method simple: just calling CREATE OBJECT with TYPE of subclass.
Code Lines:
Lets see the code lines on how to implement this:
REPORT znp_dp_factory_method.
*&---------------------------------------------------------------------*
*& Purpose: Factory method Design Pattern
*& Author : Naimesh Patel
*&---------------------------------------------------------------------*
*=====
CLASS ophandler DEFINITION ABSTRACT.
PUBLIC SECTION.
CLASS-METHODS: factory
IMPORTING iv_output_type TYPE kschl
RETURNING value(ro_obj) TYPE REF TO ophandler.
METHODS: process_output ABSTRACT.
ENDCLASS. "ophandler DEFINITION
*=====
CLASS ophandler_zabc DEFINITION INHERITING FROM ophandler.
PUBLIC SECTION.
METHODS: process_output REDEFINITION.
ENDCLASS. "ophandler_zabc DEFINITION
*
CLASS ophandler_zabc IMPLEMENTATION.
METHOD process_output.
WRITE: / 'Processing ZABC'.
ENDMETHOD. "process_output
ENDCLASS. "ophandler_zabc IMPLEMENTATION
*
CLASS ophandler IMPLEMENTATION.
METHOD factory.
CASE iv_output_type.
WHEN 'ZABC'.
* This could be very complex logic to instantiate the object
* so, this wrapper will make sure all that complexity is
* hidden from the consumer.
CREATE OBJECT ro_obj TYPE ophandler_zabc.
WHEN 'ZXYZ'.
"create another object
WHEN OTHERS.
" raise exception
ENDCASE.
ENDMETHOD. "factory
ENDCLASS. "ophandler IMPLEMENTATION
*=====
CLASS lcl_main_app DEFINITION.
PUBLIC SECTION.
CLASS-METHODS: run.
ENDCLASS. "lcl_main_app DEFINITION
*
CLASS lcl_main_app IMPLEMENTATION.
METHOD run.
DATA: lo_output TYPE REF TO ophandler.
lo_output = ophandler=>factory( 'ZABC' ).
lo_output->process_output( ).
ENDMETHOD. "run
ENDCLASS. "lcl_main_app IMPLEMENTATION
START-OF-SELECTION.
lcl_main_app=>run( ).
No comments:
Post a Comment