Lesson 7.2 · 25 min
Design patterns
Swap parking prices at runtime, try to break a vending machine built from State classes, undo and redo through a Command stack, and match six problems to the pattern that fits, all in Java.
The idea in plain words
Design patterns are named, well-tested solutions to problems that come up again and again, like recipes. Knowing the names lets you explain a design in one word: “pricing is a Strategy”.
The problem it solves
The same design problems keep coming back: swapping algorithms, reacting to events, building complex objects. Reinventing a solution each time is slow, and explaining it takes long.
How it works
- Learn a pattern as three things: the problem it solves, its shape in code, and when not to use it.
- Spot the problem in your design: “several ways to compute a price”, “behaviour depends on order status”.
- Apply the shape: an interface with one class per variant, one class per state, and so on.
- Name it out loud so the interviewer immediately knows the structure.
Example
Shipping cost differs for standard, express and international. Strategy pattern: a ShippingCost interface with three classes. Adding “same-day” is a new class, and the checkout code doesn’t change.
Key terms
- Strategy
- Swap one algorithm for another behind the same interface.
- State
- An object changes its behaviour when its state changes, with one class per state.
- Observer
- Objects subscribe to events and are told when something happens.
- Factory
- One place that decides which class to create.
- Decorator
- Wrap an object to add behaviour without changing its class.
- Code smell
- A sign of a design problem, such as a giant switch statement on a type.
In this lesson you'll learn
- The ten patterns that come up in low-level design interviews, grouped by what they solve.
- How Strategy, State and Command work, by running them: swap pricing, drive a vending machine, undo and redo.
- When each pattern helps, when it's overkill, and how to tell look-alikes apart.
Sections
- Theory: the ten
- Theory: Strategy
- Theory: State
- Theory: Command
- Theory: the rest
- Design: pick a pattern
- Check yourself
Cheat sheet
| Varying algorithm | Strategy |
|---|---|
| Lifecycle rules | State |
| Undo / queue actions | Command |
| Add behaviour by wrapping | Decorator |
| One instance | inject it, avoid Singleton |
The interactive simulations and the quiz load with JavaScript.