Design a Deck of Cards
0%
Editorial Solution
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
Suit Enum
Rank Enum
Card as Comparable
Design Patterns
Factory Method: Deck Creation
Strategy Pattern: Card Comparison
Iterator Pattern: Hand Traversal
Define Class Members / Write Code
Card (Immutable Value Object)
Hand
Deck with Thread Safety
DeckFactory
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Thread-Safe Dealing
Multi-Table Game Server
Flexible Card Comparison
Create/Explain Your Diagrams
Future Improvements
Table of Contents
A deck of cards seems like a simple collection: 52 objects in a list. But a well-designed card system must guarantee that every card is unique, that shuffling is provably fair (every permutation equally likely), that dealing removes cards atomically from the deck, and that multiple players drawing from the same deck concurrently never receive the same card. The design challenge is building an immutable value object (Card) and a thread-safe container (Deck) that work together correctly.
Interview Dialogue
Functional Requirements
- Standard 52-Card Deck - Generate all 52 cards as the cross product of 4 suits (Hearts, Diamonds, Clubs, Spades) and 13 ranks (Ace through King). Each card is unique and immutable once created.
- Shuffle - Randomize the order of all cards in the deck using the Fisher-Yates shuffle algorithm, ensuring every permutation is equally likely.
- Deal Cards - Remove cards from the top of the deck and distribute them to player hands. Track remaining cards. Reject deal requests when the deck is empty or has insufficient cards.
- Manage Player Hands - Players hold a collection of dealt cards. Support adding, removing, viewing, and sorting cards in a hand. Enforce hand-size limits when required by game rules.
Non-Functional Requirements
- Thread Safety - In multiplayer games, multiple threads may request cards from the same deck concurrently. Deal and shuffle operations must be synchronized to prevent duplicate cards being dealt.
- Extensibility - The design should support non-standard decks (Jokers, Tarot, Uno) and different game rules without modifying core classes.
Do not reshuffle already dealt cards back into the live deck just because shuffle() was called mid-game. Fairness means randomizing only the undealt portion. Once a card is in a player's hand, it has left the deck until an explicit reset.
Picture a poker game starting. The dealer opens a fresh pack of cards, shuffles, and deals five cards to each player. Each card has a suit and a rank. Those are fixed sets, so they become Suit and Rank enums. A single card combining one suit and one rank is an immutable Card value object. The full pack is a Deck that supports shuffle and deal. Each player's collection is a Hand with add, remove, and sort operations. When the casino wants to switch from standard poker to a Joker-wild variant, a DeckFactory creates the right deck type without the game knowing the difference. Not every noun survives. "Shuffle" is behavior on Deck rather than a standalone class, but the nouns give you a strong starting lineup.
The natural question is: why separate Card from Deck? Because Card is an identity (King of Hearts) while Deck is a container with ordering and thread-safe access. Mixing these concerns would mean Card knows about dealing, or Deck knows about suits.
Each card has a Suit and a Rank. Both are fixed sets. Suits are Hearts, Diamonds, Clubs, Spades. Ranks are Ace through King. These become enums because the sets are closed and known at compile time. A Card combines one Suit and one Rank into an immutable value object.
Why is Card immutable? Once you deal the King of Hearts, it must stay the King of Hearts forever. If Card were mutable, code could accidentally change a dealt card's rank, silently corrupting a player's hand. Immutability makes Cards inherently thread-safe because no thread can modify them.
The Deck holds an ordered collection of Cards. It supports shuffle(), deal(), and remainingCards(). Internally it uses a list and a topIndex pointer: dealing advances the pointer rather than removing elements from the list, which is more efficient.
A Hand holds a player's dealt cards. It supports add, remove, sort, and view. Hands are mutable because the player's collection changes during play (drawing, discarding).
A DeckFactory creates standard and custom decks. createStandardDeck() generates the 52-card cross product. createDeckWithJokers() adds two Joker cards. The factory centralizes creation logic so Deck does not need to know how cards are generated.
Why a dedicated Suit class instead of folding its responsibilities into Rank? Separating them means Suit can change independently. When you add a new feature to Suit, you do not risk breaking Rank logic.
Composition: Deck owns its Card collection
When a Deck is created, it owns all 52 Cards. Cards exist within the context of this Deck. When the Deck is reset, all cards return to their initial positions within this Deck.
Transfer of Ownership: Deck to Hand
When a card is dealt, it moves from Deck to Hand. The Deck no longer provides access to it (topIndex advances past it). The Hand now holds the reference. This is a transfer of custody, not shared ownership. A card belongs to at most one container at a time.
Association: Card references Suit and Rank enums
Card holds a Suit and a Rank, but these are enum constants, not objects with lifecycle. The relationship is a field reference, not ownership. Suit.HEARTS exists independently of any Card.
Factory creates Deck
DeckFactory creates Deck instances. The factory has no ongoing relationship with the Deck after creation. It is a creation-only dependency.
Aggregation: Game has Deck and Hands
A card game holds a Deck and multiple Hands. The Deck and Hands have independent lifecycles in some designs (a Deck can be reused across multiple rounds). This is aggregation rather than strict composition.
Why is Card-to-Deck a transfer of ownership rather than shared reference? If both Deck and Hand held references to the same card simultaneously, dealing from the Deck could give the same card to two players. Exclusive ownership - advancing topIndex removes Deck access - guarantees each card belongs to exactly one container.
With the relationships clear, the natural question is: what does the class hierarchy actually look like? Let's walk through each type from the bottom up.
Suit Enum
Four values. Each suit could carry a display name and symbol for rendering, but the core model needs only the four constants.
Rank Enum
Each rank carries a numeric value for comparison and sorting. Note that Ace is 1, but in many games Ace can be high (14). This context-dependent ranking is why a Comparator<Card> strategy is better than hardcoding rank order in the Card class itself.
Card as Comparable
Card implements Comparable<Card>, comparing by suit first, then by rank value. This provides a default sorting order (all Hearts together, sorted by rank). Games that need different orderings (trump suits, Ace-high) provide a custom Comparator<Card> instead of modifying Card.
Why does Card implement both equals/hashCode and Comparable? equals/hashCode determine identity: two cards with the same suit and rank are the same card. compareTo determines ordering: when sorting a hand, cards need a total order. These are different concerns, but both are needed for a fully functional value object.
Why does Rank store an explicit value field instead of using ordinal()? If someone reorders the enum declaration to put KING first, ordinal() silently changes from 12 to 0. All comparisons break with no compiler warning. An explicit value field is stable regardless of declaration order.
Factory Method: Deck Creation
Without a factory, every game that needs a deck must know how to generate 52 cards. Poker creates its own deck. Blackjack creates its own deck. If you add Jokers, you modify every game. The factory centralizes this:
Games request the deck type they need without knowing how cards are generated.
Strategy Pattern: Card Comparison
Different games rank cards differently. Rather than modifying Card, each game provides a Comparator<Card>:
This keeps Card unchanged across all games.
Iterator Pattern: Hand Traversal
Hand exposes its cards through an unmodifiable list or an Iterator. Callers can traverse the hand without accessing the internal ArrayList directly. This prevents external code from adding or removing cards outside of Hand's control.
The Factory pattern is the key extensibility point. Adding a Tarot deck (78 cards, 22 Major Arcana) requires one new factory method. Deck, Card, Hand, and all existing games remain untouched.
Implement immutable Card and atomic Deck.dealHand() before working on factories or hand sorting. Those two pieces prove the core invariants: card identity never changes, and a multi-card deal either succeeds as one operation or fails cleanly.
Card (Immutable Value Object)
In interviews, emphasize that Card is a value object. Say: 'Card has no setters, final fields, and overrides equals/hashCode by field values. It is inherently thread-safe and structurally incapable of mutation.'
Both fields are final. No setters exist. Once constructed, a Card never changes. This makes Card inherently thread-safe. With the building block defined, the natural question is: where do dealt cards go?
Hand
getCards() returns an unmodifiable view. Callers can read but not modify the hand through this reference. Modifications go through addCard() and removeCard(), which are controlled entry points. Now we need the container that holds all cards before dealing.
Deck with Thread Safety
The shuffle only shuffles cards from topIndex to the end. Already-dealt cards (before topIndex) are not touched. This means you can shuffle the remaining deck mid-game without affecting dealt cards. The Deck accepts a list of Cards in its constructor - but who creates that list?
DeckFactory
The nested loop generates all 52 combinations. The factory could have additional methods for Joker decks, double decks, or custom sets.
Run and Test
Browse the complete solution code and run it. Try modifying the code to experiment with the design.
Single Responsibility Principle
- Card represents identity (suit + rank) and nothing else. It does not know about decks, hands, or games.
- Deck manages the collection, shuffling, and dealing. It does not know about game rules or scoring.
- Hand manages a player's cards. It does not know about the deck or other players.
- DeckFactory handles deck creation. It does not manage dealt cards or game state.
Open/Closed Principle
- Adding a Tarot deck requires one new factory method in DeckFactory. Deck, Card, and Hand require no modification.
- Adding a
Comparator<Card>for Bridge ranking requires one new class. Card.compareTo() is unchanged. - Adding a JokerCard (if extending Card) integrates seamlessly because Deck and Hand operate on Card references.
Liskov Substitution Principle
- If JokerCard extends Card, it must honor all Card contracts: equals(), hashCode(), compareTo(), getSuit(), getRank(). Deck and Hand work with Card references and never downcast, so any Card subtype is fully interchangeable.
Interface Segregation Principle
Comparable<Card>has one method. Implementations are never forced to implement unrelated methods.- If a GameRules interface were added, it would have focused methods for each game concern, not a monolithic interface.
Dependency Inversion Principle
- Deck depends on Card (the abstraction), not on specific card types. It accepts
List<Card>in its constructor, so any card set works. - Game logic depends on GameRules interface, not on concrete PokerRules or BlackjackRules.
Thread-Safe Dealing
The duplicate-deal race condition, step by step:
- Thread-A (Player 1) calls deck.deal(). It reads topIndex = 5 and retrieves cards.get(5), the Six of Hearts.
- Thread-B (Player 2) calls deck.deal() simultaneously. It also reads topIndex = 5 (not yet incremented by Thread-A) and retrieves cards.get(5), the same Six of Hearts.
- Thread-A increments topIndex to 6. Thread-B also increments topIndex to 6 (or to 7 depending on timing).
- Both players now hold the Six of Hearts. Cards at index 6 may have been skipped entirely.
- The game state is corrupted: duplicate cards and missing cards.
The Deck class uses a ReentrantLock to serialize all mutating operations. deal() and shuffle() acquire the lock before accessing the card list and topIndex. The lock is released in a finally block to guarantee release even if an exception occurs.
The dealHand() method is particularly important: it checks remaining count and deals multiple cards within a single lock acquisition, ensuring the entire hand deal is atomic. Without this, a thread could pass the availability check but find the deck depleted by another thread before all cards are dealt.
Multi-Table Game Server
For a game server running many tables simultaneously, each table has its own Deck instance with its own lock. Tables are independent, so contention is limited to players at the same table. A server with 1,000 tables has 1,000 independent locks, enabling full parallelism across tables.
Flexible Card Comparison
The Comparator<Card> strategy allows each game to define its own ranking without touching Card. Poker uses Ace-high. Blackjack treats face cards as 10. Bridge has trump suit precedence. Each game provides its comparator at runtime.
Junior: identify the duplicate-deal race condition.
Mid-level: explain why dealHand() must be atomic and why per-table locking maximizes throughput.
Senior: discuss how to implement a multi-deck shoe with card counting prevention and reshuffling triggers.
Why fine-grained locking instead of a single global lock? A global lock serializes all operations - only one thread can do anything at a time. Per-resource locks let operations on different resources proceed in parallel, scaling throughput linearly with the number of independent resources.
Below is the class diagram for the deck of cards system.
Key points to highlight in an interview:
- Card is immutable with final fields and value-based equality. It is the core building block.
- Deck uses composition (filled diamond) because it owns its cards. Hand uses aggregation (open diamond) because cards transfer from Deck to Hand during dealing.
- DeckFactory has a dashed dependency arrow because it creates Decks but has no ongoing relationship.
- The diagram has no inheritance hierarchy for Card. Unless you need Jokers or special cards, keeping Card as a single final class is simpler and avoids the complexity of polymorphic card types.
Game-Specific Rules Engine
Define a GameRules interface with methods for hand evaluation, scoring, and win conditions. Poker, Blackjack, and Bridge each implement this interface using the same Card, Deck, and Hand classes. A generic GameEngine accepts GameRules and orchestrates the game without knowing the specific rules.
Multi-Deck Shoe
For games like Blackjack, combine multiple standard decks into a single shoe. A Shoe class wraps Deck with additional tracking for penetration depth and automatic reshuffling triggers. The factory provides createShoe(int numDecks).
Card Comparison Strategies
Different games rank cards differently. Ace-high for Poker, face cards as 10 for Blackjack, trump suit precedence for Bridge. A Comparator<Card> strategy allows plugging game-specific ranking without modifying the Card class itself.
Network Multiplayer
A game server manages multiple tables. Each table has its own Deck, Hands, and GameRules. Players connect via WebSocket. Moves are validated server-side against the game rules. The Card/Deck/Hand classes remain unchanged because they are transport-agnostic.
Persistent Game State
Serialize game state (deck order, dealt cards, hands, scores) to a database for crash recovery. When the server restarts, it reconstructs the Deck with the saved card order and topIndex, restores Hands, and resumes the game from the exact point of interruption.
Try this problem yourself
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
0%
Editorial Solution
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
Suit Enum
Rank Enum
Card as Comparable
Design Patterns
Factory Method: Deck Creation
Strategy Pattern: Card Comparison
Iterator Pattern: Hand Traversal
Define Class Members / Write Code
Card (Immutable Value Object)
Hand
Deck with Thread Safety
DeckFactory
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Thread-Safe Dealing
Multi-Table Game Server
Flexible Card Comparison
Create/Explain Your Diagrams
Future Improvements