Learning path · 5 · intermediate
GoF creational patterns
Five ways to stop object creation from being scattered all over your code: from Factory Method through Abstract Factory, Builder and Prototype to Singleton – with examples in C#, TypeScript, Java, Go and Python.
- Factory Method – let the subclass decide what gets created
Factory Method separates the algorithm that uses an object from the decision about which exact object is created. A ticket booking example in C#, TypeScript, Java, Go and Python.
Start here: one overridable method decides what gets created.
- Abstract Factory – whole families of objects that fit together
Abstract Factory creates a complete set of related objects from one family and makes sure nobody mixes parts from different sets. An example with two payment provider integrations.
Whole families of matching objects.
- Builder – complex objects step by step
Builder collects an object's parameters in readable steps and hands over a finished, valid product only in build(). A catering order example in C#, TypeScript, Java, Go and Python.
Complex objects assembled step by step.
- Prototype – a new object as a copy of a ready-made template
Prototype creates objects by cloning a configured instance instead of building them from scratch. We explain the difference between shallow and deep copies using exam templates as an example.
Creating by copying a configured instance.
- Singleton – one instance, and the reasons to hand it to a DI container
Singleton guarantees that a class has exactly one instance available to the whole application. We show thread-safe implementations in five languages and explain why today it is usually better to register the object as a singleton in a DI…
One instance – and why a DI container usually does it better.