Design patterns·topic 2 of 10
Making things
Construction looks like the boring half until the constructor has nine arguments, the object is half-built for a moment, or two tests fight over the one instance. These are the patterns for deciding what gets built, by whom, and when.
Read in order · tick what you already know
- 01
someone described a solution in four words and everyone in the room pictured roughly the same code.
Design pattern
- 02
somebody says a pattern is 'GoF' and means it came from the 1994 book rather than from a framework.
Gang of Four
- 03
the patterns reference each other, so choosing one narrows what you would sensibly choose next.
Pattern language
- 04
one function takes a string and returns the right implementation, and everyone calls it instead of choosing themselves.
Simple factory
- 05
the class has private constructors and a set of named methods that build it, so the call site says what kind you wanted.
Static factory method
- 06
the base class does the work and calls a method for the object it needs, and each subclass answers that with a different class.
Factory method
- 07
you swap one object at startup and the whole family of things it creates changes together, consistently.
Abstract factory
- 08
there are six constructors, each calling the next with one more default, and you count commas to find your argument.
Telescoping constructor
- 09
you set five things by name across five lines and call build, and the object does not exist until the last one.
Builder pattern
- 10
every method returns the object again, so the calls chain into something that reads almost like a sentence.
Fluent interface
- 11
instead of building a new one from scratch you copy an existing configured one and change two fields.
Prototype pattern
- 12
you copied the object, edited the copy's list, and the original's list changed too.
Deep copy vs shallow copy
- 13
two tests passed on their own and failed together, because the thing they both reached for kept state between them.
Singleton
- 14
the object is not created and destroyed, it is borrowed and given back, and forgetting to give it back exhausts everything.
Object pool
- 15
the field is null until the first person asks for it, and the first person asking pays for it.
Lazy initialisation
- 16
the code checks whether it is initialised, takes a lock, and checks again — and the second check is not redundant.
Double-checked locking