Factory Method & Abstract Factory
Intermediate · 20 min read · Low-Level Design, Creational Patterns
Decoupling creation from use: simple factory, factory method and families of products.
The idea in plain words
A factory is one place in your code whose job is to create objects. The rest of the code asks the factory for "a notifier for SMS" and gets one back, without knowing or caring which class was used.
Why factories exist
new ConcreteClass() hard-wires a dependency on a concrete type. If the type depends on configuration, input or platform, scattering new across the code spreads that decision everywhere:
Simple Factory (not a GoF pattern, but the one you'll use most)
One switch in one place is acceptable — that's the factory's job. The problem in the "before" code was the same decision duplicated everywhere.
Factory Method
The textbook definition: define an interface for creating an object, but let subclasses decide which class to instantiate.
Abstract Factory
Intent: provide an interface for creating families of related objects without specifying their concrete classes.
Choosing between them
Designs often start with Factory Method (simple, subclass-driven) and evolve toward Abstract Factory, Prototype or Builder as flexibility needs grow. Abstract Factories are frequently implemented with a set of factory methods, and are often single instances.
Pros and cons
Interview questions
- What's the difference between Factory Method and Abstract Factory?
- Isn't a switch statement in a factory a violation of the Open/Closed Principle?
- Why might you prefer a static factory method over a public constructor?
Further reading
Key takeaways
- Factories centralise creation so clients depend on abstractions.
- Simple factory: one method maps input to an implementation; use a registry to avoid growing switches.
- Factory Method: subclasses override a creation step inside a base-class algorithm.
- Abstract Factory: one object creates a consistent family of products; easy to add families, hard to add product types.