Factory Pattern

Learn about the factory design pattern and how to use it.

Description

The factory design pattern is a creational pattern that provides an interface or base class for creating objects but delegates the responsibility of instantiation to its subclasses. It allows for the creation of objects without exposing the instantiation logic to the client code, providing a level of abstraction and decoupling between the client and the concrete classes.

It consists of a factory class or method that encapsulates the object creation process. This factory class or method is responsible for creating instances of different types of objects based on the client’s requirements. It hides the details of object creation and provides a consistent interface for creating objects, regardless of their specific implementations.

When to use

Let us look at a few scenarios when we want to use the factory pattern.

  • Abstract data modeling: Use when we want to create objects without specifying the exact class of the object that will be created.

  • Centralize instantiation: Use when we want to centralize object creation and avoid scattering the creation code throughout the application.

  • Simplify and standardize instantiation: Use when we want to provide a common interface for creating different types of objects.

When not to use

Avoid using the factory pattern in the following scenarios:

  • Limited data types: Avoid using when the number of object types is fixed and unlikely to change.

  • Basic data structures: Avoid using when the object creation logic is simple and does not require additional flexibility or customization.

Sample code

Much like our builder pattern example, we are trying to build vehicles here again, but our approach is slightly different. We now know what parameters a certain car must take, and, therefore, we instantiate different vehicles using factory functions.

Get hands-on with 1200+ tech skills courses.