Code Implementation
Implementation Overview
We'll implement the Movie Ticket Booking System class by class, following our class diagram exactly. Every class in the diagram appears in the code, and every method has a direct requirements trace.
Implementation order:
- Enums — SeatType, ShowSeatStatus, BookingStatus, PaymentStatus, PaymentMethod, Genre, Language (R1, R4, R10, R8)
- Venue layer — Seat, Screen, Theatre (R2, R3)
- Scheduling layer — Movie, Show, ShowSeat — the critical bridge class (R1, R5, R6)
- Booking layer — Payment, Booking (R7, R8, R9, R10)
- Interfaces — PricingStrategy, NotificationService (R12, R13)
- Strategy implementations — StandardPricing, PeakHourPricing (R12)
- BookingService — the orchestrating facade (R6, R7, R8, R9)
- Usage example — complete booking flow from theatre setup to seat confirmation
Each section explains why the class exists and how it connects to the rest of the system before showing the code.
Enums — Type-Safe Constants
We define six enums that appear throughout the system. Each is an enum because it represents a fixed, closed set of values known at compile time. Using strings like "PREMIUM" or "CONFIRMED" instead would invite typos, break switch/match statements, and lose type safety.
The most important enums are ShowSeatStatus (AVAILABLE/HELD/BOOKED) and BookingStatus (PENDING/CONFIRMED/CANCELLED/EXPIRED) — they drive the two state machines from our state machine diagram.
from enum import Enum
class SeatType(Enum):
"""Physical seat category — determines base pricing."""
STANDARD = "STANDARD"
PREMIUM = "PREMIUM"
VIP = "VIP"
class ShowSeatStatus(Enum):
"""Per-show seat availability (state machine: AVAILABLE → HELD → BOOKED)."""
AVAILABLE = "AVAILABLE"
HELD = "HELD"
BOOKED = "BOOKED"
class BookingStatus(Enum):
"""Booking lifecycle (state machine: PENDING → CONFIRMED/CANCELLED/EXPIRED)."""
PENDING = "PENDING"
CONFIRMED = "CONFIRMED"
CANCELLED = "CANCELLED"
EXPIRED = "EXPIRED"
class PaymentStatus(Enum):
"""Payment processing states."""
PENDING = "PENDING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
REFUNDED = "REFUNDED"
class PaymentMethod(Enum):
CREDIT_CARD = "CREDIT_CARD"
DEBIT_CARD = "DEBIT_CARD"
UPI = "UPI"
NET_BANKING = "NET_BANKING"
class Genre(Enum):
ACTION = "ACTION"
COMEDY = "COMEDY"
DRAMA = "DRAMA"
HORROR = "HORROR"
THRILLER = "THRILLER"
ROMANCE = "ROMANCE"
SCI_FI = "SCI_FI"
class Language(Enum):
ENGLISH = "ENGLISH"
HINDI = "HINDI"
TAMIL = "TAMIL"
TELUGU = "TELUGU"
KANNADA = "KANNADA"public enum SeatType {
STANDARD, PREMIUM, VIP
}
public enum ShowSeatStatus {
AVAILABLE, HELD, BOOKED
}
public enum BookingStatus {
PENDING, CONFIRMED, CANCELLED, EXPIRED
}
public enum PaymentStatus {
PENDING, COMPLETED, FAILED, REFUNDED
}
public enum PaymentMethod {
CREDIT_CARD, DEBIT_CARD, UPI, NET_BANKING
}
public enum Genre {
ACTION, COMEDY, DRAMA, HORROR, THRILLER, ROMANCE, SCI_FI
}
public enum Language {
ENGLISH, HINDI, TAMIL, TELUGU, KANNADA
}Venue Layer — Seat, Screen, Theatre
The venue layer models the physical infrastructure that exists independently of any movie or show. A Theatre composes multiple Screen objects (a screen cannot exist without its theatre), and each Screen composes multiple Seat objects.
A Seat represents a physical chair — it has a fixed row, number, and type. It does not track availability (that's ShowSeat's job). This separation is deliberate: the same physical seat 5C exists for the 3 PM show and the 7 PM show, but its availability is different for each. The Seat stays immutable; the per-show state lives in ShowSeat.
import uuid
from datetime import datetime, timedelta
from abc import ABC, abstractmethod
class Seat:
"""Physical seat in a screen — immutable after creation."""
def __init__(self, row: str, number: int, seat_type: SeatType):
self._seat_id: str = str(uuid.uuid4())
self._row: str = row
self._number: int = number
self._seat_type: SeatType = seat_type
@property
def seat_id(self) -> str:
return self._seat_id
@property
def row(self) -> str:
return self._row
@property
def number(self) -> int:
return self._number
@property
def seat_type(self) -> SeatType:
return self._seat_type
def __repr__(self) -> str:
return f"Seat({self._row}{self._number}, {self._seat_type.value})"
class Screen:
"""A screen within a theatre — composes its seats."""
def __init__(self, name: str, seats: list[Seat]):
self._screen_id: str = str(uuid.uuid4())
self._name: str = name
self._seats: list[Seat] = list(seats) # defensive copy
@property
def screen_id(self) -> str:
return self._screen_id
@property
def name(self) -> str:
return self._name
@property
def seats(self) -> list[Seat]:
return list(self._seats) # return copy to protect composition
@property
def total_seats(self) -> int:
return len(self._seats)
class Theatre:
"""A theatre that composes multiple screens."""
def __init__(self, name: str, address: str):
self._theatre_id: str = str(uuid.uuid4())
self._name: str = name
self._address: str = address
self._screens: list[Screen] = []
@property
def theatre_id(self) -> str:
return self._theatre_id
@property
def name(self) -> str:
return self._name
@property
def screens(self) -> list[Screen]:
return list(self._screens)
def add_screen(self, screen: Screen) -> None:
self._screens.append(screen)import java.util.UUID;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Seat {
private final String seatId;
private final String row;
private final int number;
private final SeatType seatType;
public Seat(String row, int number, SeatType seatType) {
this.seatId = UUID.randomUUID().toString();
this.row = row;
this.number = number;
this.seatType = seatType;
}
public String getSeatId() { return seatId; }
public String getRow() { return row; }
public int getNumber() { return number; }
public SeatType getSeatType() { return seatType; }
@Override
public String toString() {
return "Seat(" + row + number + ", " + seatType + ")";
}
}
public class Screen {
private final String screenId;
private final String name;
private final List<Seat> seats;
public Screen(String name, List<Seat> seats) {
this.screenId = UUID.randomUUID().toString();
this.name = name;
this.seats = new ArrayList<>(seats); // defensive copy
}
public String getScreenId() { return screenId; }
public String getName() { return name; }
public List<Seat> getSeats() { return Collections.unmodifiableList(seats); }
public int getTotalSeats() { return seats.size(); }
}
public class Theatre {
private final String theatreId;
private final String name;
private final String address;
private final List<Screen> screens;
public Theatre(String name, String address) {
this.theatreId = UUID.randomUUID().toString();
this.name = name;
this.address = address;
this.screens = new ArrayList<>();
}
public String getTheatreId() { return theatreId; }
public String getName() { return name; }
public List<Screen> getScreens() { return Collections.unmodifiableList(screens); }
public void addScreen(Screen screen) {
screens.add(screen);
}
}Scheduling Layer — Movie, Show, ShowSeat
Movie is a simple data class — title, genre, language, duration. It exists independently of any screening.
Show links a Movie to a Screen at a specific time. When a Show is created, it automatically generates ShowSeat objects for every physical Seat in that Screen.
ShowSeat is the critical bridge class — the most important design decision in the entire system. It pairs a physical Seat with a specific Show to track per-show availability. Without it, we'd have no way to distinguish "seat 5C in the 3 PM show" from "seat 5C in the 7 PM show". The ShowSeat is the object that transitions through the state machine: AVAILABLE → HELD → BOOKED.
class Movie:
"""Movie metadata — independent of any screening."""
def __init__(self, title: str, genre: Genre, language: Language,
duration_minutes: int):
self._movie_id: str = str(uuid.uuid4())
self._title: str = title
self._genre: Genre = genre
self._language: Language = language
self._duration_minutes: int = duration_minutes
@property
def movie_id(self) -> str:
return self._movie_id
@property
def title(self) -> str:
return self._title
@property
def genre(self) -> Genre:
return self._genre
@property
def language(self) -> Language:
return self._language
@property
def duration_minutes(self) -> int:
return self._duration_minutes
def __repr__(self) -> str:
return f"Movie('{self._title}', {self._genre.value})"
class ShowSeat:
"""Bridge class: links a physical Seat to a specific Show.
Tracks per-show availability via the ShowSeatStatus state machine.
"""
def __init__(self, seat: Seat, show: 'Show'):
self._show_seat_id: str = str(uuid.uuid4())
self._seat: Seat = seat
self._show: 'Show' = show
self._status: ShowSeatStatus = ShowSeatStatus.AVAILABLE
self._held_at: datetime | None = None
self._held_by_booking: 'Booking | None' = None
@property
def show_seat_id(self) -> str:
return self._show_seat_id
@property
def seat(self) -> Seat:
return self._seat
@property
def status(self) -> ShowSeatStatus:
return self._status
def hold(self, booking: 'Booking') -> bool:
"""Transition: AVAILABLE → HELD. Returns False if not available."""
if self._status != ShowSeatStatus.AVAILABLE:
return False
self._status = ShowSeatStatus.HELD
self._held_at = datetime.now()
self._held_by_booking = booking
return True
def book(self) -> bool:
"""Transition: HELD → BOOKED. Called when payment succeeds."""
if self._status != ShowSeatStatus.HELD:
return False
self._status = ShowSeatStatus.BOOKED
self._held_at = None
self._held_by_booking = None
return True
def release(self) -> None:
"""Transition: HELD/BOOKED → AVAILABLE. Called on cancel/expire."""
self._status = ShowSeatStatus.AVAILABLE
self._held_at = None
self._held_by_booking = None
def __repr__(self) -> str:
return (f"ShowSeat({self._seat.row}{self._seat.number}, "
f"{self._status.value})")
class Show:
"""A screening of a Movie on a Screen at a specific time.
Composes ShowSeat objects — one per physical seat in the screen.
"""
def __init__(self, movie: Movie, screen: Screen, start_time: datetime):
self._show_id: str = str(uuid.uuid4())
self._movie: Movie = movie
self._screen: Screen = screen
self._start_time: datetime = start_time
# Generate one ShowSeat per physical seat
self._show_seats: list[ShowSeat] = [
ShowSeat(seat, self) for seat in screen.seats
]
@property
def show_id(self) -> str:
return self._show_id
@property
def movie(self) -> Movie:
return self._movie
@property
def screen(self) -> Screen:
return self._screen
@property
def start_time(self) -> datetime:
return self._start_time
@property
def show_seats(self) -> list[ShowSeat]:
return list(self._show_seats)
def get_available_seats(self) -> list[ShowSeat]:
"""Returns ShowSeats in AVAILABLE status."""
return [
ss for ss in self._show_seats
if ss.status == ShowSeatStatus.AVAILABLE
]
def get_show_seat_by_seat_id(self, seat_id: str) -> ShowSeat | None:
"""Find ShowSeat by its physical seat ID."""
for ss in self._show_seats:
if ss.seat.seat_id == seat_id:
return ss
return Noneimport java.time.LocalDateTime;
import java.util.stream.Collectors;
public class Movie {
private final String movieId;
private final String title;
private final Genre genre;
private final Language language;
private final int durationMinutes;
public Movie(String title, Genre genre, Language language, int durationMinutes) {
this.movieId = UUID.randomUUID().toString();
this.title = title;
this.genre = genre;
this.language = language;
this.durationMinutes = durationMinutes;
}
public String getMovieId() { return movieId; }
public String getTitle() { return title; }
public Genre getGenre() { return genre; }
public Language getLanguage() { return language; }
public int getDurationMinutes() { return durationMinutes; }
@Override
public String toString() {
return "Movie('" + title + "', " + genre + ")";
}
}
public class ShowSeat {
private final String showSeatId;
private final Seat seat;
private final Show show;
private ShowSeatStatus status;
private LocalDateTime heldAt;
private Booking heldByBooking;
public ShowSeat(Seat seat, Show show) {
this.showSeatId = UUID.randomUUID().toString();
this.seat = seat;
this.show = show;
this.status = ShowSeatStatus.AVAILABLE;
}
public String getShowSeatId() { return showSeatId; }
public Seat getSeat() { return seat; }
public ShowSeatStatus getStatus() { return status; }
/** Transition: AVAILABLE → HELD. Returns false if not available. */
public boolean hold(Booking booking) {
if (status != ShowSeatStatus.AVAILABLE) return false;
status = ShowSeatStatus.HELD;
heldAt = LocalDateTime.now();
heldByBooking = booking;
return true;
}
/** Transition: HELD → BOOKED. Called when payment succeeds. */
public boolean book() {
if (status != ShowSeatStatus.HELD) return false;
status = ShowSeatStatus.BOOKED;
heldAt = null;
heldByBooking = null;
return true;
}
/** Transition: HELD/BOOKED → AVAILABLE. Called on cancel/expire. */
public void release() {
status = ShowSeatStatus.AVAILABLE;
heldAt = null;
heldByBooking = null;
}
@Override
public String toString() {
return "ShowSeat(" + seat.getRow() + seat.getNumber() + ", " + status + ")";
}
}
public class Show {
private final String showId;
private final Movie movie;
private final Screen screen;
private final LocalDateTime startTime;
private final List<ShowSeat> showSeats;
public Show(Movie movie, Screen screen, LocalDateTime startTime) {
this.showId = UUID.randomUUID().toString();
this.movie = movie;
this.screen = screen;
this.startTime = startTime;
// Generate one ShowSeat per physical seat
this.showSeats = new ArrayList<>();
for (Seat seat : screen.getSeats()) {
showSeats.add(new ShowSeat(seat, this));
}
}
public String getShowId() { return showId; }
public Movie getMovie() { return movie; }
public Screen getScreen() { return screen; }
public LocalDateTime getStartTime() { return startTime; }
public List<ShowSeat> getShowSeats() { return Collections.unmodifiableList(showSeats); }
public List<ShowSeat> getAvailableSeats() {
return showSeats.stream()
.filter(ss -> ss.getStatus() == ShowSeatStatus.AVAILABLE)
.collect(Collectors.toList());
}
public ShowSeat getShowSeatBySeatId(String seatId) {
return showSeats.stream()
.filter(ss -> ss.getSeat().getSeatId().equals(seatId))
.findFirst()
.orElse(null);
}
}Booking Layer — Payment and Booking
Payment is separated from Booking following the Single Responsibility Principle — the Booking tracks what was booked (which show, which seats, for whom); the Payment tracks how it was paid (method, amount, status). A Booking composes exactly one Payment (created when payment is initiated).
The Booking class is the heart of the system. It holds references to the User, the Show, and the list of ShowSeat objects that were reserved. It transitions through the BookingStatus state machine: PENDING → CONFIRMED / CANCELLED / EXPIRED.
User is intentionally simple — just an ID, name, and email. In a real system it would connect to an authentication module, but for LLD, this is sufficient.
class User:
"""Minimal user representation for the booking domain."""
def __init__(self, name: str, email: str):
self._user_id: str = str(uuid.uuid4())
self._name: str = name
self._email: str = email
@property
def user_id(self) -> str:
return self._user_id
@property
def name(self) -> str:
return self._name
@property
def email(self) -> str:
return self._email
class Payment:
"""Payment details — separate from Booking per SRP."""
def __init__(self, amount: float, method: PaymentMethod):
self._payment_id: str = str(uuid.uuid4())
self._amount: float = amount
self._method: PaymentMethod = method
self._status: PaymentStatus = PaymentStatus.PENDING
self._created_at: datetime = datetime.now()
@property
def payment_id(self) -> str:
return self._payment_id
@property
def amount(self) -> float:
return self._amount
@property
def status(self) -> PaymentStatus:
return self._status
def complete(self) -> None:
self._status = PaymentStatus.COMPLETED
def fail(self) -> None:
self._status = PaymentStatus.FAILED
def refund(self) -> None:
self._status = PaymentStatus.REFUNDED
class Booking:
"""Tracks a user's seat reservation for a specific show.
State machine: PENDING → CONFIRMED / CANCELLED / EXPIRED.
"""
HOLD_DURATION_MINUTES: int = 8 # configurable hold timeout
def __init__(self, user: User, show: Show, show_seats: list[ShowSeat]):
self._booking_id: str = str(uuid.uuid4())
self._user: User = user
self._show: Show = show
self._show_seats: list[ShowSeat] = list(show_seats)
self._status: BookingStatus = BookingStatus.PENDING
self._payment: Payment | None = None
self._created_at: datetime = datetime.now()
@property
def booking_id(self) -> str:
return self._booking_id
@property
def user(self) -> User:
return self._user
@property
def show(self) -> Show:
return self._show
@property
def show_seats(self) -> list[ShowSeat]:
return list(self._show_seats)
@property
def status(self) -> BookingStatus:
return self._status
@property
def payment(self) -> 'Payment | None':
return self._payment
@property
def created_at(self) -> datetime:
return self._created_at
def is_hold_expired(self) -> bool:
"""Check if the hold period has elapsed."""
if self._status != BookingStatus.PENDING:
return False
expiry = self._created_at + timedelta(
minutes=self.HOLD_DURATION_MINUTES
)
return datetime.now() > expiry
def confirm(self, payment: Payment) -> None:
"""Transition: PENDING → CONFIRMED."""
self._status = BookingStatus.CONFIRMED
self._payment = payment
def cancel(self) -> None:
"""Transition: PENDING/CONFIRMED → CANCELLED."""
self._status = BookingStatus.CANCELLED
def expire(self) -> None:
"""Transition: PENDING → EXPIRED (timeout)."""
self._status = BookingStatus.EXPIRED
def __repr__(self) -> str:
return (f"Booking({self._booking_id[:8]}, "
f"{self._status.value}, seats={len(self._show_seats)})")import java.time.Duration;
public class User {
private final String userId;
private final String name;
private final String email;
public User(String name, String email) {
this.userId = UUID.randomUUID().toString();
this.name = name;
this.email = email;
}
public String getUserId() { return userId; }
public String getName() { return name; }
public String getEmail() { return email; }
}
public class Payment {
private final String paymentId;
private final double amount;
private final PaymentMethod method;
private PaymentStatus status;
private final LocalDateTime createdAt;
public Payment(double amount, PaymentMethod method) {
this.paymentId = UUID.randomUUID().toString();
this.amount = amount;
this.method = method;
this.status = PaymentStatus.PENDING;
this.createdAt = LocalDateTime.now();
}
public String getPaymentId() { return paymentId; }
public double getAmount() { return amount; }
public PaymentStatus getStatus() { return status; }
public void complete() { status = PaymentStatus.COMPLETED; }
public void fail() { status = PaymentStatus.FAILED; }
public void refund() { status = PaymentStatus.REFUNDED; }
}
public class Booking {
private static final int HOLD_DURATION_MINUTES = 8;
private final String bookingId;
private final User user;
private final Show show;
private final List<ShowSeat> showSeats;
private BookingStatus status;
private Payment payment;
private final LocalDateTime createdAt;
public Booking(User user, Show show, List<ShowSeat> showSeats) {
this.bookingId = UUID.randomUUID().toString();
this.user = user;
this.show = show;
this.showSeats = new ArrayList<>(showSeats);
this.status = BookingStatus.PENDING;
this.createdAt = LocalDateTime.now();
}
public String getBookingId() { return bookingId; }
public User getUser() { return user; }
public Show getShow() { return show; }
public List<ShowSeat> getShowSeats() { return Collections.unmodifiableList(showSeats); }
public BookingStatus getStatus() { return status; }
public Payment getPayment() { return payment; }
public LocalDateTime getCreatedAt() { return createdAt; }
public boolean isHoldExpired() {
if (status != BookingStatus.PENDING) return false;
LocalDateTime expiry = createdAt.plusMinutes(HOLD_DURATION_MINUTES);
return LocalDateTime.now().isAfter(expiry);
}
public void confirm(Payment payment) {
this.status = BookingStatus.CONFIRMED;
this.payment = payment;
}
public void cancel() { this.status = BookingStatus.CANCELLED; }
public void expire() { this.status = BookingStatus.EXPIRED; }
@Override
public String toString() {
return "Booking(" + bookingId.substring(0, 8) + ", " +
status + ", seats=" + showSeats.size() + ")";
}
}PricingStrategy Interface and Implementations
The PricingStrategy interface is the Strategy Pattern in action (Fundamentals S12). Different strategies calculate ticket prices differently — a standard strategy uses base prices per seat type, while a peak-hour strategy applies a time-based multiplier.
The BookingService holds a PricingStrategy reference and delegates pricing to it. Adding a new strategy (e.g., "holiday pricing", "loyalty discount") requires implementing the interface — no existing code changes. This is the Open/Closed Principle at work.
class PricingStrategy(ABC):
"""Strategy interface — different algorithms for ticket pricing."""
@abstractmethod
def calculate_price(self, show_seats: list[ShowSeat],
show: Show) -> float:
"""Calculate total price for the given seats in a show."""
pass
class StandardPricing(PricingStrategy):
"""Base pricing by seat type."""
BASE_PRICES: dict[SeatType, float] = {
SeatType.STANDARD: 200.0,
SeatType.PREMIUM: 350.0,
SeatType.VIP: 500.0,
}
def calculate_price(self, show_seats: list[ShowSeat],
show: Show) -> float:
return sum(
self.BASE_PRICES[ss.seat.seat_type] for ss in show_seats
)
class PeakHourPricing(PricingStrategy):
"""Applies a multiplier during peak hours (6 PM - 10 PM)."""
PEAK_MULTIPLIER: float = 1.5
PEAK_START_HOUR: int = 18
PEAK_END_HOUR: int = 22
def __init__(self, base_strategy: PricingStrategy):
self._base_strategy: PricingStrategy = base_strategy
def calculate_price(self, show_seats: list[ShowSeat],
show: Show) -> float:
base = self._base_strategy.calculate_price(show_seats, show)
hour = show.start_time.hour
if self.PEAK_START_HOUR <= hour < self.PEAK_END_HOUR:
return base * self.PEAK_MULTIPLIER
return baseimport java.util.Map;
import java.util.HashMap;
public interface PricingStrategy {
double calculatePrice(List<ShowSeat> showSeats, Show show);
}
public class StandardPricing implements PricingStrategy {
private static final Map<SeatType, Double> BASE_PRICES = new HashMap<>();
static {
BASE_PRICES.put(SeatType.STANDARD, 200.0);
BASE_PRICES.put(SeatType.PREMIUM, 350.0);
BASE_PRICES.put(SeatType.VIP, 500.0);
}
@Override
public double calculatePrice(List<ShowSeat> showSeats, Show show) {
return showSeats.stream()
.mapToDouble(ss -> BASE_PRICES.get(ss.getSeat().getSeatType()))
.sum();
}
}
public class PeakHourPricing implements PricingStrategy {
private static final double PEAK_MULTIPLIER = 1.5;
private static final int PEAK_START_HOUR = 18;
private static final int PEAK_END_HOUR = 22;
private final PricingStrategy baseStrategy;
public PeakHourPricing(PricingStrategy baseStrategy) {
this.baseStrategy = baseStrategy;
}
@Override
public double calculatePrice(List<ShowSeat> showSeats, Show show) {
double base = baseStrategy.calculatePrice(showSeats, show);
int hour = show.getStartTime().getHour();
if (hour >= PEAK_START_HOUR && hour < PEAK_END_HOUR) {
return base * PEAK_MULTIPLIER;
}
return base;
}
}NotificationService Interface
The NotificationService is an Observer-style interface — the BookingService notifies it when bookings are confirmed, cancelled, or expired. The interface decouples the booking logic from the notification mechanism. In production, this could be email, SMS, push notifications, or all three — the BookingService doesn't know or care.
We provide a simple ConsoleNotificationService for demonstration. A real implementation would integrate with email/SMS gateways.
class NotificationService(ABC):
"""Observer interface — notified of booking lifecycle events."""
@abstractmethod
def notify_booking_confirmed(self, booking: Booking) -> None:
pass
@abstractmethod
def notify_booking_cancelled(self, booking: Booking) -> None:
pass
@abstractmethod
def notify_booking_expired(self, booking: Booking) -> None:
pass
class ConsoleNotificationService(NotificationService):
"""Simple implementation that prints to console."""
def notify_booking_confirmed(self, booking: Booking) -> None:
print(f"[NOTIFICATION] Booking {booking.booking_id[:8]} confirmed "
f"for {booking.user.name}. "
f"Seats: {len(booking.show_seats)} | "
f"Movie: {booking.show.movie.title}")
def notify_booking_cancelled(self, booking: Booking) -> None:
print(f"[NOTIFICATION] Booking {booking.booking_id[:8]} cancelled "
f"for {booking.user.name}.")
def notify_booking_expired(self, booking: Booking) -> None:
print(f"[NOTIFICATION] Booking {booking.booking_id[:8]} expired "
f"for {booking.user.name}. Seats have been released.")public interface NotificationService {
void notifyBookingConfirmed(Booking booking);
void notifyBookingCancelled(Booking booking);
void notifyBookingExpired(Booking booking);
}
public class ConsoleNotificationService implements NotificationService {
@Override
public void notifyBookingConfirmed(Booking booking) {
System.out.println("[NOTIFICATION] Booking " +
booking.getBookingId().substring(0, 8) + " confirmed for " +
booking.getUser().getName() + ". Seats: " +
booking.getShowSeats().size() + " | Movie: " +
booking.getShow().getMovie().getTitle());
}
@Override
public void notifyBookingCancelled(Booking booking) {
System.out.println("[NOTIFICATION] Booking " +
booking.getBookingId().substring(0, 8) + " cancelled for " +
booking.getUser().getName() + ".");
}
@Override
public void notifyBookingExpired(Booking booking) {
System.out.println("[NOTIFICATION] Booking " +
booking.getBookingId().substring(0, 8) + " expired for " +
booking.getUser().getName() + ". Seats have been released.");
}
}BookingService — The Orchestrating Facade
The BookingService is the Facade that orchestrates the entire booking workflow. It's the single entry point for creating bookings, making payments, cancelling bookings, and handling hold expirations. It coordinates between Show, ShowSeat, Booking, Payment, PricingStrategy, and NotificationService.
The service implements the two-phase booking flow from our sequence diagram:
- Phase 1 (Hold):
create_booking()— validate seats, hold them, create a PENDING booking - Phase 2 (Pay):
make_payment()— check hold validity, process payment, confirm booking
And the cleanup paths:
cancel_booking()— release seats, cancel/refundexpire_holds()— system timer releases expired holds
class BookingService:
"""Facade — orchestrates the complete booking workflow."""
def __init__(self, pricing_strategy: PricingStrategy,
notification_service: NotificationService):
self._pricing_strategy: PricingStrategy = pricing_strategy
self._notification_service: NotificationService = notification_service
self._bookings: dict[str, Booking] = {}
def create_booking(self, user: User, show: Show,
seat_ids: list[str]) -> Booking:
"""Phase 1: Hold seats and create a PENDING booking."""
# Resolve ShowSeats from seat IDs
show_seats: list[ShowSeat] = []
for seat_id in seat_ids:
show_seat = show.get_show_seat_by_seat_id(seat_id)
if show_seat is None:
raise ValueError(f"Seat {seat_id} not found in show")
if show_seat.status != ShowSeatStatus.AVAILABLE:
raise ValueError(
f"Seat {show_seat.seat.row}{show_seat.seat.number} "
f"is not available (status: {show_seat.status.value})"
)
show_seats.append(show_seat)
# Create booking first (needed for hold reference)
booking = Booking(user, show, show_seats)
# Hold all seats atomically — if any fails, release all
held: list[ShowSeat] = []
for ss in show_seats:
if ss.hold(booking):
held.append(ss)
else:
# Rollback: release already-held seats
for h in held:
h.release()
raise ValueError(
f"Failed to hold seat {ss.seat.row}{ss.seat.number}"
)
self._bookings[booking.booking_id] = booking
print(f"Booking {booking.booking_id[:8]} created — "
f"{len(show_seats)} seat(s) held for {user.name}")
return booking
def make_payment(self, booking_id: str,
method: PaymentMethod) -> Payment:
"""Phase 2: Process payment and confirm booking."""
booking = self._bookings.get(booking_id)
if booking is None:
raise ValueError(f"Booking {booking_id} not found")
if booking.status != BookingStatus.PENDING:
raise ValueError(
f"Booking is {booking.status.value}, cannot pay"
)
# Guard: check hold expiration
if booking.is_hold_expired():
self._expire_booking(booking)
raise ValueError("Hold expired — booking has been expired")
# Calculate price using strategy
amount = self._pricing_strategy.calculate_price(
booking.show_seats, booking.show
)
# Process payment
payment = Payment(amount, method)
payment.complete() # Simulate successful payment
# Confirm: transition ShowSeats HELD → BOOKED
for ss in booking.show_seats:
ss.book()
booking.confirm(payment)
self._notification_service.notify_booking_confirmed(booking)
return payment
def cancel_booking(self, booking_id: str) -> None:
"""Cancel a PENDING or CONFIRMED booking."""
booking = self._bookings.get(booking_id)
if booking is None:
raise ValueError(f"Booking {booking_id} not found")
if booking.status == BookingStatus.CONFIRMED:
# Guard: only cancel before show starts
if datetime.now() >= booking.show.start_time:
raise ValueError("Cannot cancel after show has started")
# Refund payment
if booking.payment:
booking.payment.refund()
if booking.status not in (
BookingStatus.PENDING, BookingStatus.CONFIRMED
):
raise ValueError(
f"Cannot cancel booking in {booking.status.value} state"
)
# Release all seats
for ss in booking.show_seats:
ss.release()
booking.cancel()
self._notification_service.notify_booking_cancelled(booking)
def expire_holds(self) -> list[Booking]:
"""System timer: expire all bookings with elapsed holds."""
expired: list[Booking] = []
for booking in self._bookings.values():
if (booking.status == BookingStatus.PENDING
and booking.is_hold_expired()):
self._expire_booking(booking)
expired.append(booking)
return expired
def _expire_booking(self, booking: Booking) -> None:
"""Internal: expire a single booking and release its seats."""
for ss in booking.show_seats:
ss.release()
booking.expire()
self._notification_service.notify_booking_expired(booking)public class BookingService {
private final PricingStrategy pricingStrategy;
private final NotificationService notificationService;
private final Map<String, Booking> bookings;
public BookingService(PricingStrategy pricingStrategy,
NotificationService notificationService) {
this.pricingStrategy = pricingStrategy;
this.notificationService = notificationService;
this.bookings = new HashMap<>();
}
/** Phase 1: Hold seats and create a PENDING booking. */
public Booking createBooking(User user, Show show,
List<String> seatIds) {
List<ShowSeat> showSeats = new ArrayList<>();
for (String seatId : seatIds) {
ShowSeat showSeat = show.getShowSeatBySeatId(seatId);
if (showSeat == null) {
throw new IllegalArgumentException(
"Seat " + seatId + " not found in show");
}
if (showSeat.getStatus() != ShowSeatStatus.AVAILABLE) {
throw new IllegalStateException(
"Seat " + showSeat.getSeat().getRow() +
showSeat.getSeat().getNumber() + " is not available");
}
showSeats.add(showSeat);
}
Booking booking = new Booking(user, show, showSeats);
// Hold all seats atomically
List<ShowSeat> held = new ArrayList<>();
for (ShowSeat ss : showSeats) {
if (ss.hold(booking)) {
held.add(ss);
} else {
// Rollback
for (ShowSeat h : held) h.release();
throw new IllegalStateException(
"Failed to hold seat " + ss.getSeat().getRow() +
ss.getSeat().getNumber());
}
}
bookings.put(booking.getBookingId(), booking);
System.out.println("Booking " +
booking.getBookingId().substring(0, 8) +
" created — " + showSeats.size() +
" seat(s) held for " + user.getName());
return booking;
}
/** Phase 2: Process payment and confirm booking. */
public Payment makePayment(String bookingId,
PaymentMethod method) {
Booking booking = bookings.get(bookingId);
if (booking == null) {
throw new IllegalArgumentException(
"Booking " + bookingId + " not found");
}
if (booking.getStatus() != BookingStatus.PENDING) {
throw new IllegalStateException(
"Booking is " + booking.getStatus() + ", cannot pay");
}
if (booking.isHoldExpired()) {
expireBooking(booking);
throw new IllegalStateException(
"Hold expired — booking has been expired");
}
double amount = pricingStrategy.calculatePrice(
booking.getShowSeats(), booking.getShow());
Payment payment = new Payment(amount, method);
payment.complete();
for (ShowSeat ss : booking.getShowSeats()) ss.book();
booking.confirm(payment);
notificationService.notifyBookingConfirmed(booking);
return payment;
}
/** Cancel a PENDING or CONFIRMED booking. */
public void cancelBooking(String bookingId) {
Booking booking = bookings.get(bookingId);
if (booking == null) {
throw new IllegalArgumentException(
"Booking " + bookingId + " not found");
}
if (booking.getStatus() == BookingStatus.CONFIRMED) {
if (LocalDateTime.now().isAfter(booking.getShow().getStartTime())) {
throw new IllegalStateException(
"Cannot cancel after show has started");
}
if (booking.getPayment() != null) {
booking.getPayment().refund();
}
}
if (booking.getStatus() != BookingStatus.PENDING &&
booking.getStatus() != BookingStatus.CONFIRMED) {
throw new IllegalStateException(
"Cannot cancel booking in " + booking.getStatus() +
" state");
}
for (ShowSeat ss : booking.getShowSeats()) ss.release();
booking.cancel();
notificationService.notifyBookingCancelled(booking);
}
/** System timer: expire all bookings with elapsed holds. */
public List<Booking> expireHolds() {
List<Booking> expired = new ArrayList<>();
for (Booking booking : bookings.values()) {
if (booking.getStatus() == BookingStatus.PENDING &&
booking.isHoldExpired()) {
expireBooking(booking);
expired.add(booking);
}
}
return expired;
}
private void expireBooking(Booking booking) {
for (ShowSeat ss : booking.getShowSeats()) ss.release();
booking.expire();
notificationService.notifyBookingExpired(booking);
}
}Usage Example
Let's see the complete system in action — setting up a theatre, scheduling a show, and walking through the full booking lifecycle: create → pay → confirm, and a second booking that gets cancelled.
def main():
# === Setup venue ===
seats = [
Seat("A", 1, SeatType.STANDARD),
Seat("A", 2, SeatType.STANDARD),
Seat("A", 3, SeatType.PREMIUM),
Seat("B", 1, SeatType.PREMIUM),
Seat("B", 2, SeatType.VIP),
]
screen = Screen("Screen 1", seats)
theatre = Theatre("Cineplex Downtown", "123 Main St")
theatre.add_screen(screen)
# === Setup movie and show ===
movie = Movie("Inception", Genre.SCI_FI, Language.ENGLISH, 148)
show = Show(movie, screen, datetime(2025, 3, 15, 19, 0)) # 7 PM
print(f"Show: {movie.title} at {theatre.name}, {screen.name}")
print(f"Available seats: {len(show.get_available_seats())}")
print()
# === Setup services ===
pricing = PeakHourPricing(StandardPricing()) # 7 PM = peak hour
notifications = ConsoleNotificationService()
service = BookingService(pricing, notifications)
# === User 1: Full booking flow (create → pay → confirm) ===
user1 = User("Alice", "alice@example.com")
seat_ids_1 = [seats[0].seat_id, seats[2].seat_id] # A1, A3
booking1 = service.create_booking(user1, show, seat_ids_1)
print(f"Available after hold: {len(show.get_available_seats())}")
print()
payment1 = service.make_payment(booking1.booking_id,
PaymentMethod.UPI)
print(f"Payment: Rs. {payment1.amount} ({payment1.status.value})")
print(f"Booking status: {booking1.status.value}")
print(f"Available after confirm: {len(show.get_available_seats())}")
print()
# === User 2: Booking then cancel ===
user2 = User("Bob", "bob@example.com")
seat_ids_2 = [seats[4].seat_id] # B2 (VIP)
booking2 = service.create_booking(user2, show, seat_ids_2)
service.cancel_booking(booking2.booking_id)
print(f"Booking 2 status: {booking2.status.value}")
print(f"Available after cancel: {len(show.get_available_seats())}")
print()
# === Try booking an already-booked seat ===
user3 = User("Charlie", "charlie@example.com")
try:
service.create_booking(user3, show, seat_ids_1) # A1, A3 already booked
except ValueError as e:
print(f"Expected error: {e}")
if __name__ == "__main__":
main()public class Main {
public static void main(String[] args) {
// === Setup venue ===
List<Seat> seats = List.of(
new Seat("A", 1, SeatType.STANDARD),
new Seat("A", 2, SeatType.STANDARD),
new Seat("A", 3, SeatType.PREMIUM),
new Seat("B", 1, SeatType.PREMIUM),
new Seat("B", 2, SeatType.VIP)
);
Screen screen = new Screen("Screen 1", seats);
Theatre theatre = new Theatre("Cineplex Downtown", "123 Main St");
theatre.addScreen(screen);
// === Setup movie and show ===
Movie movie = new Movie("Inception", Genre.SCI_FI,
Language.ENGLISH, 148);
Show show = new Show(movie, screen,
LocalDateTime.of(2025, 3, 15, 19, 0)); // 7 PM
System.out.println("Show: " + movie.getTitle() + " at " +
theatre.getName() + ", " + screen.getName());
System.out.println("Available seats: " +
show.getAvailableSeats().size());
System.out.println();
// === Setup services ===
PricingStrategy pricing = new PeakHourPricing(
new StandardPricing()); // 7 PM = peak hour
NotificationService notifications =
new ConsoleNotificationService();
BookingService service = new BookingService(
pricing, notifications);
// === User 1: Full booking flow ===
User user1 = new User("Alice", "alice@example.com");
List<String> seatIds1 = List.of(
seats.get(0).getSeatId(),
seats.get(2).getSeatId()); // A1, A3
Booking booking1 = service.createBooking(user1, show, seatIds1);
System.out.println("Available after hold: " +
show.getAvailableSeats().size());
System.out.println();
Payment payment1 = service.makePayment(
booking1.getBookingId(), PaymentMethod.UPI);
System.out.printf("Payment: Rs. %.0f (%s)%n",
payment1.getAmount(), payment1.getStatus());
System.out.println("Booking status: " + booking1.getStatus());
System.out.println("Available after confirm: " +
show.getAvailableSeats().size());
System.out.println();
// === User 2: Booking then cancel ===
User user2 = new User("Bob", "bob@example.com");
List<String> seatIds2 = List.of(
seats.get(4).getSeatId()); // B2 (VIP)
Booking booking2 = service.createBooking(user2, show, seatIds2);
service.cancelBooking(booking2.getBookingId());
System.out.println("Booking 2 status: " + booking2.getStatus());
System.out.println("Available after cancel: " +
show.getAvailableSeats().size());
System.out.println();
// === Try booking an already-booked seat ===
User user3 = new User("Charlie", "charlie@example.com");
try {
service.createBooking(user3, show, seatIds1);
} catch (IllegalStateException e) {
System.out.println("Expected error: " + e.getMessage());
}
}
}Expected output:
Show: Inception at Cineplex Downtown, Screen 1
Available seats: 5
Booking xxxxxxxx created — 2 seat(s) held for Alice
Available after hold: 3
[NOTIFICATION] Booking xxxxxxxx confirmed for Alice. Seats: 2 | Movie: Inception
Payment: Rs. 825.0 (COMPLETED)
Booking status: CONFIRMED
Available after confirm: 3
Booking xxxxxxxx created — 1 seat(s) held for Bob
[NOTIFICATION] Booking xxxxxxxx cancelled for Bob.
Booking 2 status: CANCELLED
Available after cancel: 4
Expected error: Seat A1 is not available (status: BOOKED)
Pricing breakdown for Alice: Seat A1 (STANDARD: Rs. 200) + Seat A3 (PREMIUM: Rs. 350) = Rs. 550 base. At 7 PM (peak hour), multiplier 1.5x applied = Rs. 825.
Key observations from the output:
- After Alice holds 2 seats, available drops from 5 to 3
- After Alice pays, available stays at 3 (seats transition HELD → BOOKED, still unavailable)
- After Bob cancels, available goes back to 4 (his HELD seat is released)
- Charlie's attempt to book Alice's seats fails with a clear error message