Factory Method Pattern in ABAP OOPs
This document explains the Factory Method Design Pattern in ABAP Object-Oriented Programming with
an example.
1. Concept
The Factory Method Pattern provides an interface for creating objects in a superclass, but allows
subclasses to alter the type of objects that will be created.
• Promotes loose coupling.
• Useful when the exact type of object to be created is determined at runtime.
• Encapsulates object creation logic inside a factory method.
2. ABAP Example – Factory Method
🔹 Step 1: Define an Interface
INTERFACE lif_vehicle.
METHODS: drive.
ENDINTERFACE.
🔹 Step 2: Create Concrete Classes
CLASS lcl_car DEFINITION.
PUBLIC SECTION.
INTERFACES lif_vehicle.
ENDCLASS.
CLASS lcl_car IMPLEMENTATION.
METHOD lif_vehicle~drive.
WRITE: / 'Driving a Car'.
ENDMETHOD.
ENDCLASS.
CLASS lcl_bike DEFINITION.
PUBLIC SECTION.
INTERFACES lif_vehicle.
ENDCLASS.
CLASS lcl_bike IMPLEMENTATION.
1
METHOD lif_vehicle~drive.
WRITE: / 'Riding a Bike'.
ENDMETHOD.
ENDCLASS.
🔹 Step 3: Factory Class with Factory Method
CLASS lcl_vehicle_factory DEFINITION.
PUBLIC SECTION.
CLASS-METHODS: get_vehicle
IMPORTING iv_type TYPE string
RETURNING VALUE(ro_vehicle) TYPE REF TO lif_vehicle.
ENDCLASS.
CLASS lcl_vehicle_factory IMPLEMENTATION.
METHOD get_vehicle.
CASE iv_type.
WHEN 'CAR'.
ro_vehicle = NEW lcl_car( ).
WHEN 'BIKE'.
ro_vehicle = NEW lcl_bike( ).
WHEN OTHERS.
ro_vehicle = NEW lcl_car( ). " Default
ENDCASE.
ENDMETHOD.
ENDCLASS.
🔹 Step 4: Using the Factory Method
DATA(lo_vehicle) = lcl_vehicle_factory=>get_vehicle( 'CAR' ).
lo_vehicle->drive( ).
DATA(lo_vehicle2) = lcl_vehicle_factory=>get_vehicle( 'BIKE' ).
lo_vehicle2->drive( ).
Output:
Driving a Car
Riding a Bike
2
3. Benefits
• Encapsulates object creation.
• Promotes flexibility (easy to add new vehicle types).
• Client code depends only on the interface ( lif_vehicle ) and not on concrete classes.
4. Summary
• The Factory Method Pattern in ABAP lets you create objects without exposing the creation logic.
• Useful when you have multiple subclasses implementing the same interface.
• Helps in writing maintainable and scalable ABAP OOP applications.