Skip to content
BENIBIX Learn

Factory Pattern

Development🏗️ ArchitectureDesign Patterns

Also known as Factory Method, Factory Function, Factory

One function or class makes the objects. The callers need not know how.

Think of it like

Think of it like ordering a pizza. You say which kind, and the kitchen works out how to make it.

Example

Emma's app sends alerts by email, text or push. Her code asks the factory for the user's choice. It gets back the right sender.

Why it matters

It keeps the hard parts of making objects in one place. So new kinds are easy to add.

Definition

The factory pattern puts the job of making objects in one place. Instead of building an object directly, code asks a factory for one and says what kind it wants. The factory decides which class to use and how to set it up. The calling code never needs to know the details. Adding a new kind then means changing only the factory.

Common mistake

Adding a factory where a plain constructor would do. If there is only one kind, the factory is just one more step.

Key takeaways

  1. 1
    One place to make. All objects of a family.
  2. 2
    Ask by kind. Not by class name.
  3. 3
    Easy to extend. New kind, one change.