Factory pattern in ABAP

I couldn't find a nice ABAP blog on how to implement a Factory pattern which had my requirements, so here it is.

Requirements :

  • The factory decides which class it returns depending on the input parameters
  • Do not allow to instanciate the child classes outside the factory

Here is a diagram of the design patter : image.png

The parent class

Note that the create is protected to allow the child classes to call the super->constructor() if needed.

CLASS animal DEFINITION
  PUBLIC
  ABSTRACT
  CREATE PROTECTED .

  PUBLIC SECTION.
    METHODS constructor.
    METHODS eat.
    METHODS sleep.
ENDCLASS.

The child classes

Having the animal_factory as global friend to allow the factory to call any method of the class, especially the constructor to instanciate the class. The create is private so that they can't be instanciated anywhere else.

CLASS cat DEFINITION
  PUBLIC
  INHERITING FROM animal
  FINAL
  CREATE PRIVATE
  GLOBAL FRIENDS animal_factory.

  PUBLIC SECTION.
    METHODS constructor.
    METHODS meow.
ENDCLASS.
CLASS bird DEFINITION
  PUBLIC
  INHERITING FROM animal
  FINAL
  CREATE PRIVATE
  GLOBAL FRIENDS animal_factory.

  PUBLIC SECTION.
    METHODS constructor.
    METHODS chirp.
ENDCLASS.

The factory class

The factory has only static methods. The static method create_animal takes a structure as input and according to the parameters, it returns a different type of animal.

CLASS animal_factory DEFINITION
  PUBLIC
  ABSTRACT
  FINAL
  CREATE PRIVATE .

  PUBLIC SECTION.
    CLASS-METHODS create_animal
      IMPORTING
        parameters TYPE animal_parameters
      RETURNING VALUE(animal) TYPE REF TO animal.
ENDCLASS.

CLASS animal_factory IMPLEMENTATION.

  METHOD create_animal.
    IF parameters-has_wings = abap_true.
      animal = NEW bird().
    ELSEIF parameters-can_meow = abap_true.
      animal = NEW cat().
    ENDIF.
  ENDMETHOD.

ENDCLASS