LOW LEVEL DESIGN · STEP 5 OF 9
Creational patterns
Five ways to create objects without hard-wiring which class you get. Each lesson is an animated walkthrough with a small Java example you can run, notes and the interview questions with answers.
- 1 Singleton patternExactly one shared instance, created once and reached from one place.The Singleton pattern with a ride app fare table: eager creation, the lazy race, double-checked locking with volatile, the holder idiom and the enum singleton, why a global getInstance call hurts testing, and the cleaner habit of creating one instance at startup and passing it in.
- 2 Factory method patternLet a method, often in a subclass, decide which concrete class to create.The Factory Method pattern with a login code sender: a shared algorithm in an abstract creator, one overridable method that decides which delivery channel to create, adding a new channel without editing old code, and how it differs from a simple static factory, constructors and abstract factory.
- 3 Abstract factory patternCreate whole families of related objects that are guaranteed to match.The Abstract Factory pattern with a checkout that runs in two countries: one factory object creates a matching payment rail, tax rule and money format, so families can never be mixed. Covers the participants, Java code, choosing the factory once at startup, adding a family versus adding a product, and how it differs from factory method and builder.
- 4 Builder patternAssemble a complex object step by step, then validate it once in build().The Builder pattern with a report export request: why telescoping constructors and setter-based objects break down, a fluent builder with required fields up front, an immutable result, validation in build(), a record with a nested builder and toBuilder, and how it differs from factories, with examples from the Java standard library.
- 5 Prototype patternMake new objects by copying a configured one instead of building from scratch.The Prototype pattern with game levels: load and configure a level once, then create variants by copying it. Covers the shallow copy bug where copies share mutable parts, deep copies with a copy constructor, why clone() and Cloneable are awkward, a registry of named prototypes, and how it compares with factories and builders.