Factory Method design pattern provides unique interface to object instantiation. The decision on which object is to be instantiated is hidden from the outside world in the code. Using this approach different objects can be instantiated dynamically.
Requirements for implementing Factory method:
- Base ABSTRACT class with implemented Factory Method having at least one importing parameter to decide which sub-class to be instantiate
- Sub-classes inheriting the base abstract class
Definition of the base abstract class with factory method GET_INSTANCE
CLASS lcl_output DEFINITION ABSTRACT.
PUBLIC SECTION.
CLASS-METHODS:
get_instance
IMPORTING iv_type TYPE char4
RETURNING value(ro_result) TYPE REF TO lcl_output.
METHODS:
output ABSTRACT.
ENDCLASS.
Subclass LCL_PDF_OUTPUT inheriting the base abstract class
CLASS lcl_pdf_output DEFINITION INHERITING FROM lcl_output. PUBLIC SECTION. METHODS: output REDEFINITION. ENDCLASS. CLASS lcl_pdf_output IMPLEMENTATION. METHOD output. WRITE: / 'Printing PDF document'. ENDMETHOD. ENDCLASS.
Subclass LCL_PNG_OUTPUT inheriting the base abstract class
CLASS lcl_png_output DEFINITION INHERITING FROM lcl_output. PUBLIC SECTION. METHODS: output REDEFINITION. ENDCLASS. CLASS lcl_png_output IMPLEMENTATION. METHOD output. WRITE: / 'Generating PNG Image'. ENDMETHOD. ENDCLASS.
Implementation of the base abstract class and its factory method
CLASS lcl_output IMPLEMENTATION. METHOD get_instance. CASE iv_type. WHEN 'PDF'. CREATE OBJECT ro_result TYPE lcl_pdf_output. WHEN 'PNG'. CREATE OBJECT ro_result TYPE lcl_png_output. WHEN OTHERS. *** ERROR ENDCASE. ENDMETHOD. ENDCLASS.
Testing report
START-OF-SELECTION. DATA: lo_output TYPE REF TO lcl_output. lo_output = lcl_output=>get_instance( 'PDF' ). lo_output->output( ). lo_output = lcl_output=>get_instance( 'PNG' ). lo_output->output( ).