Designbench

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

  1. Learn a pattern as three things: the problem it solves, its shape in code, and when not to use it.
  2. Spot the problem in your design: “several ways to compute a price”, “behaviour depends on order status”.
  3. Apply the shape: an interface with one class per variant, one class per state, and so on.
  4. 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

Sections

  1. Theory: the ten
  2. Theory: Strategy
  3. Theory: State
  4. Theory: Command
  5. Theory: the rest
  6. Design: pick a pattern
  7. Check yourself

Cheat sheet

Varying algorithmStrategy
Lifecycle rulesState
Undo / queue actionsCommand
Add behaviour by wrappingDecorator
One instanceinject it, avoid Singleton

The interactive simulations and the quiz load with JavaScript.