Creational patterns
How to create objects flexibly, without coupling your code to concrete classes.
- 5patterns
- 30animated steps
- 30code examples
Creational patterns separate the code that uses an object from the code that builds it. They all answer the same question: who decides which concrete class to instantiate, and when?
The patterns
- 1Singleton
Ensure a class has only one instance and provide a global access point to it.
- 2Factory Method
Define an interface for creating an object, but let subclasses decide which concrete class to instantiate.
- 3Abstract Factory
Provide an interface for creating families of related objects without specifying their concrete classes.
- 4Builder
Construct a complex object step by step, separating its construction from its representation.
- 5Prototype
Create new objects by cloning an existing instance, without depending on its concrete class.
At a glance
| Pattern | Also known as | Use it for |
|---|---|---|
| Singleton | — | A single shared resource (logger, config, cache) |
| Factory Method | Virtual Constructor | The exact type of the objects is not known in advance |
| Abstract Factory | Kit | Several product families that must stay consistent |
| Builder | — | Objects with many optional parameters |
| Prototype | — | Expensive creation (queries, computation) but cheap copy |
Other families
-
Structural patterns
7 patterns
How to assemble classes and objects into larger structures that stay flexible.
-
Behavioral patterns
11 patterns
How objects communicate and share responsibilities.