Skip to main content

Design Patterns Applied

Editorial

Patterns Overview

Our Movie Ticket Booking System uses three design patterns. Each solves a specific problem — not just a textbook exercise, but a real engineering challenge that would cause pain during extension or maintenance if ignored.

PatternCategoryWhere AppliedProblem It Solves
StrategyBehavioralPricingStrategy → StandardPricing, PeakHourPricingDifferent shows need different pricing formulas without modifying BookingService
ObserverBehavioralNotificationService → ConsoleNotificationServiceBooking events need to notify external systems without coupling BookingService to notification channels
StateBehavioralBookingStatus state machine (PENDING → CONFIRMED/CANCELLED/EXPIRED)Booking behavior changes based on its current state, with strict transition rules

All three are Behavioral patterns — they define how objects communicate and change behavior. This is typical for transactional systems where the core challenge is managing state and workflows, not object creation (Creational) or structural composition (Structural).

Let's examine each pattern in depth: the problem it solves, how we applied it, and why alternatives are less suitable.

Strategy Pattern — Pricing

Category: Behavioral (Fundamentals S12)

The problem without this pattern:

Movie ticket pricing is not a single formula. Standard seats cost differently from VIP seats. Evening shows cost more than matinees. Weekends have surcharges. Loyalty members get discounts. Without the Strategy pattern, all these rules would live inside BookingService.make_payment():

# WITHOUT Strategy — pricing logic embedded in BookingService
def make_payment(self, booking_id, method):
    ...
    amount = 0
    for ss in booking.show_seats:
        if ss.seat.seat_type == SeatType.STANDARD:
            amount += 200
        elif ss.seat.seat_type == SeatType.PREMIUM:
            amount += 350
        elif ss.seat.seat_type == SeatType.VIP:
            amount += 500

    hour = booking.show.start_time.hour
    if 18 <= hour < 22:  # peak hour
        amount *= 1.5

    if is_weekend(booking.show.start_time):  # weekend surcharge
        amount *= 1.2
    ...

Every new pricing rule requires modifying BookingService — violating the Open/Closed Principle. The method grows into an unmaintainable tangle of conditionals. Testing pricing logic requires instantiating the entire BookingService.

How we applied it:

  1. Defined a PricingStrategy interface with one method: calculate_price(show_seats, show) -> float
  2. Implemented StandardPricing (base prices per seat type) and PeakHourPricing (wraps another strategy, applies a time-based multiplier)
  3. BookingService receives a PricingStrategy via constructor injection and delegates all pricing to it

The Decorator-like composition (PeakHourPricing wraps StandardPricing) allows stacking: PeakHourPricing(WeekendPricing(StandardPricing())) applies both multipliers without any class knowing about the others.

Why Strategy and NOT alternatives?

  • Why not just if/else? Violates OCP. Every new pricing rule changes BookingService. Pricing rules are a product decision that changes frequently — they should be pluggable.
  • Why not Template Method? Template Method uses inheritance — BookingService subclasses would override a calculate_price hook. But pricing varies independently of booking logic. We'd need PeakHourBookingService, WeekendBookingService, etc. — an explosion of subclasses.
  • Why not Factory? A factory creates objects but doesn't encapsulate algorithms. Pricing is a computation, not an object creation problem.

Observer Pattern — Notifications

Category: Behavioral (Fundamentals S11)

The problem without this pattern:

When a booking is confirmed, the system needs to send a confirmation email, possibly an SMS, update an analytics dashboard, and potentially notify a food pre-ordering system. Without Observer, BookingService must know about every downstream consumer:

# WITHOUT Observer — direct coupling to notification channels
def make_payment(self, booking_id, method):
    ...
    booking.confirm(payment)

    # BookingService now coupled to every notification system
    self._email_service.send_confirmation_email(booking)
    self._sms_service.send_confirmation_sms(booking)
    self._analytics.record_booking(booking)
    self._food_service.prompt_preorder(booking)
    ...

Every new notification channel requires modifying BookingService. The service violates SRP — it handles booking and notification routing. Testing is painful because you must mock every notification dependency.

How we applied it:

  1. Defined a NotificationService interface with methods: notify_booking_confirmed(), notify_booking_cancelled(), notify_booking_expired()
  2. BookingService holds a NotificationService reference and calls it at the appropriate lifecycle points
  3. The concrete implementation (ConsoleNotificationService) decides how to notify — email, SMS, push, or just print

This is a simplified Observer: instead of a Subject with a list of observers, we have a single interface that the BookingService notifies. For a more scalable version, you could make NotificationService a composite that delegates to a list of channel-specific notifiers.

Why Observer and NOT alternatives?

  • Why not direct method calls? Tight coupling — adding a new channel means changing BookingService. Observer decouples the "what happened" (booking confirmed) from "who needs to know" (email, SMS, analytics).
  • Why not a message queue? In a distributed system, yes — you'd publish events to a queue. But for an in-memory LLD exercise, a message queue is over-engineering. The Observer interface is the in-process equivalent of an event bus.
  • Why not the Mediator pattern? Mediator manages bidirectional communication between multiple objects. Our notifications are one-directional (BookingService → NotificationService). Observer is simpler and sufficient.

State Pattern — Booking Lifecycle

Category: Behavioral (Fundamentals S12)

The problem without this pattern:

Booking behavior depends on its current state. A PENDING booking can be paid or cancelled. A CONFIRMED booking can be cancelled (before show starts) but not paid again. An EXPIRED booking cannot be modified at all. Without the State pattern, every method checks the current state:

# WITHOUT State — conditional logic in every method
def make_payment(self, booking_id, method):
    if booking.status == BookingStatus.PENDING:
        # process payment
    elif booking.status == BookingStatus.CONFIRMED:
        raise ValueError("Already paid")
    elif booking.status == BookingStatus.CANCELLED:
        raise ValueError("Booking is cancelled")
    elif booking.status == BookingStatus.EXPIRED:
        raise ValueError("Booking has expired")

def cancel_booking(self, booking_id):
    if booking.status == BookingStatus.PENDING:
        # release seats, cancel
    elif booking.status == BookingStatus.CONFIRMED:
        if datetime.now() < booking.show.start_time:
            # release seats, refund, cancel
        else:
            raise ValueError("Show already started")
    elif booking.status == BookingStatus.CANCELLED:
        raise ValueError("Already cancelled")
    elif booking.status == BookingStatus.EXPIRED:
        raise ValueError("Cannot cancel expired booking")

Every method in BookingService has a chain of if/elif checks. Adding a new state (e.g., REFUND_PENDING) means modifying every method. The state transition rules are scattered across multiple methods — there's no single place to see the complete state machine.

How we applied it:

In our current implementation, the State pattern is applied implicitly through the enum + state machine design rather than a full-blown State class hierarchy. The BookingStatus enum defines the states, the Booking class methods (confirm(), cancel(), expire()) are the transitions, and the BookingService enforces the guards.

The state machine diagram from the previous tutorial maps directly to code:

  • Each state = a value in BookingStatus enum
  • Each transition = a method in Booking or BookingService
  • Each guard = an if check before the transition

When would we use the full State Pattern (with state classes)?

If the behavior within each state becomes complex — for example, if PENDING bookings have different discount rules than CONFIRMED bookings, or if the notification content varies by state — then promoting each state to a class with on_enter(), on_exit(), and handle_event() methods would be justified. For our current complexity, the enum approach is sufficient and simpler.

Why State and NOT alternatives?

  • Why not just if/else checks? The scattered conditionals problem described above. State centralizes transition logic.
  • Why not a lookup table / transition matrix? A dict[(from_state, event) -> to_state] would work for the transitions but doesn't capture guards or actions. It's a valid optimization for simpler state machines but lacks expressiveness for our guards like show not started.
  • Why not a state machine library? In production, using transitions (Python) or Spring State Machine (Java) is reasonable. But for an LLD interview, you should be able to implement the state machine from scratch to demonstrate understanding.

How the Patterns Work Together

The three patterns collaborate within the BookingService orchestration:

  1. A user requests a booking → BookingService.create_booking() creates a PENDING booking (State: initial transition)
  2. The user pays → BookingService.make_payment() calculates price via Strategy, transitions the booking to CONFIRMED (State), and notifies via Observer
  3. The user cancels → BookingService.cancel_booking() checks the state guard (State), releases seats, and notifies via Observer
  4. The hold expires → BookingService.expire_holds() transitions to EXPIRED (State) and notifies via Observer

The separation of concerns:

  • Strategy handles how much to charge — BookingService doesn't know the formula
  • Observer handles who to tell — BookingService doesn't know the channels
  • State handles what's allowed when — BookingService doesn't use scattered if/else chains

Each pattern removes one dimension of complexity from the BookingService, keeping it focused on orchestration — the single responsibility of coordinating the booking workflow.

SOLID compliance summary:

PrincipleHow It's Applied
S — Single ResponsibilityBookingService orchestrates; PricingStrategy prices; NotificationService notifies; Booking tracks state
O — Open/ClosedNew pricing (implement PricingStrategy) and new notification channels (implement NotificationService) require no changes to existing classes
L — Liskov SubstitutionAny PricingStrategy implementation can replace another without breaking BookingService
I — Interface SegregationPricingStrategy has one method; NotificationService has three focused methods — no fat interfaces
D — Dependency InversionBookingService depends on abstractions (PricingStrategy, NotificationService), not concrete classes