This centralization reduces duplication and enforces architectural clarity. It also simplifies testing. Instead of mocking concrete classes everywhere, you can replace the factory or inject test implementations through it. The business flow stays clean because it does not carry environment-dependent decision logic.
There are several variations of the pattern.
The Factory Method - the method inside particular class that returns the instance/s ( used a lot with Singleton and Multiton).
The Factory - separate class that is in charge of instances of other classes creation.
The Abstract Factory pattern introduces an additional abstraction level, effectively becoming a factory of factories. It provides an interface for creating families of related objects without specifying their concrete classes.
To illustrate the Factory pattern in a simple and transparent way, the example implementation consists of three main building blocks: a common interface, two concrete calculation classes, and one factory class responsible for instantiation
At the core lies the interface zif_calc_logic. It defines the contract that all calculation implementations must follow. In this case, the contract contains a single method responsible for calculating a result based on an input amount. The client never works with concrete classes directly. It only depends on this interface, which keeps the design loosely coupled and extensible.
The first concrete implementation, zcl_tax_calculator, represents tax calculation logic. It implements the shared interface and provides its own calculation rule, multiplying the input amount by a tax factor. The second implementation, zcl_discount_calculator, follows the same structure but applies a discount rule instead. Both classes are independent from the client and from each other. They share behavior only through the interface.
The central element of the pattern is zcl_calc_factory. This class encapsulates the decision logic for object creation. Its constructor is private, which prevents direct instantiation and enforces access exclusively through the static factory method get_calculator. The method receives a calculation type as input and returns a reference to the interface. Internally, it decides which concrete class to instantiate. If the type is unknown, it raises a domain-specific exception.
The full code of the example classes you can check here:
https://github.com/JuliaBerteneva/Factory.git