DEV Community


Posted on

Injectable Factory Method with Spring Boot

The Factory Design Pattern meets Dependency Injection 🏭+💉

In software engineering, the Factory pattern is a creational pattern that creates objects without exposing the creation logic to the client and refers to newly created objects using a common interface. In other words, it encapsulates object creation and decouples it from the client code that uses the objects. This can improve code maintainability, flexibility, and reusability.

For example, imagine you have a program that needs to create different types of objects, such as shapes or vehicles. You could write a bunch of conditional statements or switch statements in your client code to determine which concrete class to instantiate. However, this approach can quickly become messy and hard to extend. Instead, you could use a factory method or a factory class that takes care of the object creation based on some input parameter or logic.

Some benefits of using the Factory pattern include:
👉 Encapsulating object creation and reducing coupling
👉 Providing a central point of control and configuration for object creation
👉 Promoting the open-closed principle by allowing new subclasses to be added without modifying existing code
👉 Enabling testing and mocking of the client code without actually instantiating real objects

Dependency injection takes the factory method to the next level. Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation. This helps you to follow SOLID’s dependency inversion and single responsibility principles.

Top comments (0)