पाठ 6 / 25

Patterns That Recur in LLD

Strategy, state, observer, factory.

Four patterns and when to use them

Strategy swaps an algorithm behind an interface: pricing, elevator scheduling, spot allocation. State moves behaviour into one class per state, so a vending machine or order behaves differently in Idle versus HasMoney without big switch statements. Observer lets subscribers react to events, such as display boards updated when spots free up. Factory centralises object creation, for example creating the right Vehicle or Spot from a type. The Design Patterns course covers these in depth; in interviews, name a pattern only after showing the problem it solves.

Observer for availability updates

Python sketch.

from abc import ABC, abstractmethod

class AvailabilityListener(ABC):
    @abstractmethod
    def on_change(self, floor: int, free_spots: int) -> None: ...

class DisplayBoard(AvailabilityListener):
    def on_change(self, floor, free_spots):
        print(f"Floor {floor}: {free_spots} free")

class Floor:
    def __init__(self, number: int):
        self.number = number
        self.free = 0
        self._listeners: list[AvailabilityListener] = []

    def subscribe(self, listener: AvailabilityListener) -> None:
        self._listeners.append(listener)

    def set_free(self, count: int) -> None:
        self.free = count
        for listener in self._listeners:
            listener.on_change(self.number, count)

Patterns as vocabulary

Patterns are like chess openings: knowing the names lets you communicate quickly, but you still have to play the position in front of you.

त्वरित जाँच: A vending machine that behaves differently when idle, holding money or dispensing is a natural fit for:

  • A bigger switch statement in every method
  • The Singleton pattern
  • The Adapter pattern
  • The State pattern
Answer

The State pattern — One class per state.