PrepZone Logo
PrepZone

Strategy Pattern

Swap algorithms at runtime without touching the client.

Read these first

Why this matters

  • Interface PricingStrategy with price(Order)
  • CampusOS parking: nearest spot, cheapest spot, handicapped-first
  • Spring-style: inject strategy via constructor
  • Strategy: client chooses algorithm; often set once per operation
  • Patterns are forces and solutions — name the force before the pattern.
Creational
Factorychoose implementation
Builderstep-by-step assembly
Structural
Decoratorstack behaviour
Facadesimple entry point
Behavioral
Strategyswap algorithm
Observernotify subscribers
Statebehaviour by mode
Pick the family first, then the specific pattern.

Overview

Swap algorithms at runtime without touching the client. Study each section below in order — every list is interview-ready reference material.

Pricing strategies

Points to cover

  • Interface PricingStrategy with price(Order)
  • Implementations: Regular, StudentDiscount, PremiumMember
  • Client holds PricingStrategy field — set at runtime
  • New pricing rule = new class, zero edits to checkout flow

Spot assignment

Points to cover

  • CampusOS parking: nearest spot, cheapest spot, handicapped-first
  • Each algorithm is a SpotAssignmentStrategy
  • ParkingLot delegates to injected strategy

Registration

Points to cover

  • Spring-style: inject strategy via constructor
  • Manual: factory picks strategy from config or enum
  • Test: pass mock strategy into service under test

vs State pattern

Points to cover

  • Strategy: client chooses algorithm; often set once per operation
  • State: object changes behaviour as internal mode changes
  • Vending machine modes → State; payment calculation → Strategy
Java
// CampusOS — apply "Pricing strategies" on paper first, then in code
public final class StrategyPatternExample {
    // 1. Name entities from the problem statement
    // 2. Draw relationships before writing methods
    // 3. Introduce patterns only when a force appears
}

Quick recall

Everything you need if you only revisit this box.

  1. Pricing strategies — review this slice before mock interviews.
  2. Spot assignment — review this slice before mock interviews.
  3. Registration — review this slice before mock interviews.
  4. vs State pattern — review this slice before mock interviews.

Test yourself

Answer these before moving on — recall is what makes it stick.