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
- π€ Client Request — Requests an object
⬇️ - π Factory Class — Decides which object to create
⬇️ - 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
CREATE OBJECT lo_car.π΄ High Coupling: Client knows which class object is being created.
✅ Factory Pattern Approach
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