Design patterns·topic 5 of 10
Who calls whom, and when
These are the patterns about the flow of control rather than the shape of the objects: swapping an algorithm, reacting to a change, turning a request into a thing you can queue, undo or log.
Read in order · tick what you already know
- 01
the class takes the algorithm as a constructor argument, and choosing a different one is a different argument.
Strategy pattern
- 02
the base class runs the five steps in order and leaves two of them abstract for you to write.
Template method
- 03
the object's behaviour changed after a call and nothing branched — it had swapped the object it was delegating to.
State pattern
- 04
you wrote down every state and every allowed move between them, and three combinations you had shipped turned out to be impossible.
State machine
- 05
the same switch on type appeared in four methods, and adding a case meant finding all four.
Replace conditional with polymorphism
- 06
the invalid cases return in the first four lines, and the rest of the method is not indented at all.
Guard clause
- 07
instead of returning null you returned something that implements the interface and does nothing, and the null checks disappeared.
Null object
- 08
you changed one field and four other things updated, and finding out which four meant reading a subscription list.
Observer pattern
- 09
you passed a function in and something else decided when to call it, possibly twice, possibly never.
Callback
- 10
the six components stopped calling each other and all called one object in the middle instead.
Mediator pattern
- 11
the request became an object with an execute method, so you could put it in a queue, log it and undo it.
Command pattern
- 12
the object handed out an opaque snapshot of itself that only it can read, and later took it back to undo.
Memento pattern
- 13
the request went to the first handler, which passed it on, and somewhere down the line something answered it.
Chain of responsibility
- 14
you walked the collection without knowing whether it was an array, a tree or a paged remote call.
Iterator pattern
- 15
one version hands you each element and you decide when to stop; the other takes your function and runs the loop itself.
Internal vs external iterator
- 16
the function paused in the middle, handed back a value, and carried on from that exact line when asked for the next.
Generator
- 17
you added a new operation over the whole tree by writing one class, and did not touch any of the node types.
Visitor pattern
- 18
the method that runs depends on the runtime types of two objects, and one call was not enough to get there.
Double dispatch
- 19
each node in the parsed expression knows how to evaluate itself, and evaluating the root walks the whole tree.
Interpreter pattern