Factory Pattern in Clean ABAP
A working abapGit project demonstrating the GoF Factory Method pattern with interfaces, abstract classes, and modern ABAP object orientation.
Why Factory?
The Factory Method pattern lets you decouple the creation of an object from the
use of it. Instead of NEW zcl_car( ) scattered across your code, you call
lo_factory->create_vehicle( 'CAR' ) and the factory decides which concrete
class to instantiate.
Benefits in ABAP:
- Swap implementations without touching call sites
- Unit-test business logic against a mock factory
- Register new vehicle types without modifying existing code (Open/Closed)
Project Structure
This repository is a complete abapGit project — you can pull it directly into your system. The core objects are:
| Object | Type | Description |
|---|---|---|
ZIF_VEHICLE | Interface | Contract every vehicle must fulfill |
ZCL_VEHICLE_FACTORY | Class | Creates the right vehicle by type key |
ZCL_CAR | Class | Car implementation |
ZCL_TRUCK | Class | Truck implementation |
The Interface
ZIF_VEHICLE defines two methods that every vehicle must implement:
INTERFACE zif_vehicle PUBLIC.
METHODS:
get_type
RETURNING VALUE(rv_type) TYPE string,
describe
RETURNING VALUE(rv_desc) TYPE string.
ENDINTERFACE.
The Factory
ZCL_VEHICLE_FACTORY has a single static method. Adding a new vehicle type
means adding one WHEN branch — existing callers are unaffected:
METHOD create_vehicle.
ro_vehicle = SWITCH #( iv_type
WHEN 'CAR' THEN NEW zcl_car( )
WHEN 'TRUCK' THEN NEW zcl_truck( )
ELSE RAISE EXCEPTION TYPE cx_sy_create_object_error ).
ENDMETHOD.
Usage Example
DATA(lo_factory) = NEW zcl_vehicle_factory( ).
DATA(lo_car) = lo_factory->create_vehicle( 'CAR' ).
DATA(lo_truck) = lo_factory->create_vehicle( 'TRUCK' ).
WRITE: / lo_car->describe( ). " 'Sedan, 4 doors, 90kW'
WRITE: / lo_truck->describe( ). " 'Semi, 18 wheels, 320kW'
Unit Testing
The test class in zcl_vehicle_factory.clas.testclasses.abap uses the standard
ABAP Unit framework with no mocks needed — the factory is pure and testable as-is:
METHOD test_car_type.
DATA(lo_v) = zcl_vehicle_factory=>create_vehicle( 'CAR' ).
cl_abap_unit_assert=>assert_equals(
exp = 'CAR'
act = lo_v->get_type( ) ).
ENDMETHOD.
Clone into Your System
- Open abapGit in your SAP system
- Create a new online repo pointing to this repository’s URL
- Pull — all objects land in package
ZFACTORY_DEMO