Tuesday, July 7, 2026

🏭 What is a Factory Pattern? Create Objects the Smart Way! πŸš€

 The Factory Pattern is a Creational Design Pattern that provides a way to create objects without exposing the object creation logic to the client.

Instead of creating objects directly using CREATE OBJECT, the Factory Pattern uses a dedicated factory class to create and return the required object.


πŸ“– Definition

The Factory Pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

πŸ‘‰ It hides the object creation logic and returns the required object.


πŸ”Ή How Factory Pattern Works

  1. πŸ‘€ Client Request — Requests an object
    ⬇️
  2. 🏭 Factory Class — Decides which object to create
    ⬇️
  3. Returns the required object:
    πŸš— Car Object | 🏍️ Bike Object | 🚚 Truck Object


πŸ”Ή Why Use Factory Pattern?

  • πŸ”— Loose Coupling — Client is not tightly coupled with concrete classes
  • πŸ”§ Better Maintainability — Changes in object creation logic don't affect client code
  • 🧩 Improved Flexibility — Easy to introduce new types of objects
  • πŸ§ͺ Easier Testing — Objects can be easily mocked or replaced
  • ♻️ Reusable Logic — Centralized object creation logic can be reused


⚖️ Traditional Approach vs Factory Pattern Approach

❌ Traditional Approach

DATA lo_car TYPE REF TO zcl_car.
CREATE OBJECT lo_car.

πŸ”΄ High Coupling: Client knows which class object is being created.

✅ Factory Pattern Approach

DATA lo_vehicle TYPE REF TO zif_vehicle.
lo_vehicle =
  zcl_vehicle_factory=>get_vehicle( 'CAR' ).

🟒 Low Coupling: Client requests the object, factory decides which object to create.


🌍 Real-Life Example

🏭 Vehicle Factory ➡️ πŸš— Car | 🏍️ Bike | 🚚 Truck

πŸ’‘ Customer requests a vehicle. Factory creates and returns the required vehicle.


πŸ’» Example (ABAP)

INTERFACE zif_vehicle.
  METHODS drive.
ENDINTERFACE.

CLASS zcl_car DEFINITION.
  PUBLIC SECTION.
    INTERFACES zif_vehicle.
ENDCLASS.

CLASS zcl_vehicle_factory DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS get_vehicle
      IMPORTING iv_type TYPE string
      RETURNING VALUE(ro_vehicle)
        TYPE REF TO zif_vehicle.
ENDCLASS.


πŸ”Ή Where Is It Used?

  • πŸ“¦ RAP Frameworks — Used to create handler / service objects
  • ☁️ SAP BTP Applications — Manage services and components creation dynamically
  • 🏒 Enterprise Applications — Create objects based on business scenarios
  • ⚙️ Service Classes — Factory used to create service implementations
  • πŸ‘₯ Dependency Injection — Helps in decoupling and unit testing


πŸ’‘ Key Takeaway

Factory Pattern helps developers create objects in a flexible, maintainable and scalable way without being dependent on concrete classes.

🎯 Factory Pattern = Create Objects Smartly, Not Directly!


πŸ’¬ Have you implemented Factory Pattern in your ABAP projects? Share your experience below!

No comments:

Post a Comment