AlgoViz

Which pattern, when

medium 45 min

A pattern is an answer to one kind of pressure.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:38

See it run

Forces first, then three patterns at work, then the whole matrix.

Operations

Force to pattern

Six pressures. For each, the cheap answer and the pattern.

Step 1 of 7

Start with the pressure

What variesCheap answerPattern
a formula, chosen outside
behaviour by phase
who hears of a change
which class to create
extras in any mix
an action to undo

The left column is what you hear in the requirements. Nothing is chosen yet.

Step 1: Start with the pressure

def choose(force):    cheap, pattern = ANSWERS[force.what]    if force.differs == "value":        return "a table of values"    if force.differs == "moves" or force.examples < 2:        return cheap    return pattern
Force
what varies
Cheap answer
try it first

Cover the right columns and say them yourself.

In the real world

The same which pattern, when doing real jobs. Pick one and step through it.

One job of 30 pages travels through five patterns that nobody needed.

Step 1 of 5

Get the instance

maincallershopSingletonmakerJobFactorybuilderJobBuilderpricingPriceStrategyjobJobpagesnonegetInstance()

main asks a global object.

Step 1: Get the instance

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Pattern before force

    critical

    Every class must be explained, and there is no reason to give.

    Wrong
    class PriceStrategyFactory: ...class PerPageStrategy: ...
    Right
    def price(pages):    return pages * 10
  • A class where a number differs

    major

    Three classes with the same code and other constants.

    Wrong
    class ChildPrice:    def cents(self): return 500class AdultPrice:    def cents(self): return 1000
    Right
    PRICE = {"child": 500, "adult": 1000}
  • Singleton for a single example

    major

    Global data hides who uses it and leaks between tests.

    Wrong
    lot = ParkingLot.get_instance()
    Right
    lot = ParkingLot(spots)gate = Gate(lot)
  • News before the change

    critical

    If the move is refused, people were told something false.

    Wrong
    self._tell(job)job.fire(event)
    Right
    job.fire(event)self._tell(job)
  • One guard around all listeners

    major

    The first broken listener silences the rest.

    Wrong
    try:    for f in listeners: f(job)except Exception: pass
    Right
    for f in list(listeners):    try: f(job)    except Exception as e: log(e)

Interview tips

  • Say four things

    • Force.
    • Pattern.
    • Cost.
    • Exit.
  • Cheap first

    • A value.
    • A function.
    • A table.
  • Look-alikes

    • Adapter translates.
    • Decorator adds.
    • Proxy controls.
  • Warning signs

    • One implementation.
    • A name ending in Manager and Factory.
    • No sentence from the prompt behind it.