All topics
Patternsintermediate

Factory Pattern

Using a function or method to create and return objects, encapsulating the object-creation logic away from the calling code.

The Factory pattern centers on using a dedicated function (a 'factory function' or a static factory method) to construct and return objects, rather than having calling code invoke a constructor directly with new. The core benefit is decoupling *what kind* of object gets created from the calling code that needs one, which becomes especially valuable when object creation involves conditional logic, configuration, or should be swappable/testable independently from the code consuming the created objects.

A factory function is like ordering a 'sandwich' from a specific sandwich-shop counter rather than personally choosing and assembling every individual ingredient yourself — you describe roughly what you want, and the counter (factory) decides internally exactly how to build the specific item, handing you a finished product without you needing to know or care about its internal assembly steps.

Key Concepts

1
A simple factory function might take a type parameter and internally decide which of several related object 'shapes' or classes to instantiate and return, hiding that branching logic from every call site that just wants 'a shape' without caring about the specific instantiation details. This is especially useful when the created objects don't share a rigid class hierarchy but do share a common usage interface — the factory can return plain objects, class instances, or a mix, as long as they conform to whatever shape the calling code expects.
type
2
Factories are also valuable for testing: a factory function can be swapped out (mocked) more easily than a hardcoded new SomeClass() call scattered throughout a codebase, since consuming code depends on 'whatever the factory returns' rather than a specific concrete class, making it straightforward to substitute a test double during unit tests without touching the consuming code's internals.
new SomeClass()
3
In JavaScript specifically, factory functions are also a common alternative to classes altogether for creating objects with private state via closures (blurring into the module/factory-function pattern) rather than needing this, new, or prototype-based inheritance at all — some style guides and codebases prefer this factory-function approach specifically to sidestep this-binding footguns entirely, since a factory-created object's methods can capture their needed state directly via closure instead of relying on a correctly-bound this.
thisnew