1. The Hook (The "Byte-Sized" Intro)
- In a Nutshell: Chain of Responsibility = pass request along chain until handled (support tickets: L1→L2→L3), State = behavior changes with state (vending machine states), Iterator = sequential access without exposing structure (Java Iterator), Mediator = centralized communication (chat room).
- Benefits: Decoupling, flexibility, controlled access.
- Use: Chain for request handling, State for state machines, Iterator for traversal, Mediator for complex interactions!
Chain = escalation ladder (junior→senior→manager). State = traffic light (red→green→yellow, behavior changes). Iterator = TV channel surfing (next/previous). Mediator = air traffic control (planes don't talk directly, all through tower)!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy
- Chain: Customer service tiers (L1→L2→L3)
- State: Mood states (happy→sad→angry, act differently)
- Iterator: Book pages (flip one by one)
- Mediator: Real estate agent (buyer↔agent↔seller)
3. Technical Mastery (The "Deep Dive")
java
// ===========================================
// 1. CHAIN OF RESPONSIBILITY
// ===========================================
// Handler
abstract class SupportHandler {
protected SupportHandler next;
void setNext(SupportHandler handler) {
this.next = handler;
}
abstract void handleRequest(int level);
}
// Concrete handlers
class Level1Support extends SupportHandler {
void handleRequest(int level) {
if (level <= 1) {
System.out.println("L1 handled");
} else if (next != null) {
next.handleRequest(level);
}
}
}
class Level2Support extends SupportHandler {
void handleRequest(int level) {
if (level <= 2) {
System.out.println("L2 handled");
} else if (next != null) {
next.handleRequest(level);
}
}
}
class Level3Support extends SupportHandler {
void handleRequest(int level) {
System.out.println("L3 handled");
}
}
// Usage:
SupportHandler l1 = new Level1Support();
SupportHandler l2 = new Level2Support();
SupportHandler l3 = new Level3Support();
l1.setNext(l2);
l2.setNext(l3);
l1.handleRequest(3); // Passed to L3
// ===========================================
// 2. STATE PATTERN
// ===========================================
// State interface
interface VendingMachineState {
void insertCoin();
void dispense();
}
// Concrete states
class NoCoinState implements VendingMachineState {
public void insertCoin() {
System.out.println("Coin inserted");
}
public void dispense() {
System.out.println("Insert coin first!");
}
}
class HasCoinState implements VendingMachineState {
public void insertCoin() {
System.out.println("Coin already inserted");
}
public void dispense() {
System.out.println("Dispensing product");
}
}
// Context
class VendingMachine {
private VendingMachineState state;
private VendingMachineState noCoinState = new NoCoinState();
private VendingMachineState hasCoinState = new HasCoinState();
VendingMachine() {
state = noCoinState;
}
void insertCoin() {
state.insertCoin();
state = hasCoinState;
}
void dispense() {
state.dispense();
state = noCoinState;
}
}
// Usage:
VendingMachine vm = new VendingMachine();
vm.dispense(); // Insert coin first!
vm.insertCoin();
vm.dispense(); // Dispensing product
// ===========================================
// 3. ITERATOR PATTERN
// ===========================================
// Iterator interface
interface Iterator<T> {
boolean hasNext();
T next();
}
// Collection
class BookCollection {
private List<String> books = new ArrayList<>();
void addBook(String book) {
books.add(book);
}
Iterator<String> iterator() {
return new BookIterator();
}
// Inner class iterator
private class BookIterator implements Iterator<String> {
private int index = 0;
public boolean hasNext() {
return index < books.size();
}
public String next() {
return books.get(index++);
}
}
}
// Usage:
BookCollection collection = new BookCollection();
collection.addBook("Book 1");
collection.addBook("Book 2");
Iterator<String> it = collection.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// Java's Iterator:
List<String> list = List.of("A", "B", "C");
java.util.Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
// ===========================================
// 4. MEDIATOR PATTERN
// ===========================================
// Mediator
interface ChatMediator {
void sendMessage(String message, User user);
void addUser(User user);
}
// Concrete mediator
class ChatRoom implements ChatMediator {
private List<User> users = new ArrayList<>();
public void addUser(User user) {
users.add(user);
}
public void sendMessage(String message, User sender) {
for (User user : users) {
if (user != sender) {
user.receive(message);
}
}
}
}
// Colleague
class User {
private String name;
private ChatMediator mediator;
User(String name, ChatMediator mediator) {
this.name = name;
this.mediator = mediator;
}
void send(String message) {
System.out.println(name + " sends: " + message);
mediator.sendMessage(message, this);
}
void receive(String message) {
System.out.println(name + " received: " + message);
}
}
// Usage:
ChatMediator chatRoom = new ChatRoom();
User alice = new User("Alice", chatRoom);
User bob = new User("Bob", chatRoom);
chatRoom.addUser(alice);
chatRoom.addUser(bob);
alice.send("Hi Bob!"); // Bob receives5. The Comparison & Decision Layer
| Pattern | Use When |
|---|---|
| Chain of Responsibility | Request handling with fallback (logging, filters) |
| State | Behavior changes based on state (TCP connection, game states) |
| Iterator | Sequential traversal without exposing structure |
| Mediator | Complex object interactions (chat, UI components) |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question: "State vs Strategy?" Answer:
- State: Object changes behavior based on internal state
- Strategy: Client chooses algorithm/behavior
java
// State: Behavior changes with state
VendingMachine vm = new VendingMachine();
vm.insertCoin(); // State changes internally
vm.dispense(); // Different behavior now
// Strategy: Client chooses
cart.setPaymentStrategy(new CreditCardPayment()); // Explicit choicePro-Tip: Java's built-in Iterator:
java
// All collections provide iterator()
List<String> list = Arrays.asList("A", "B", "C");
// Traditional
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// Enhanced for-loop (uses iterator internally!)
for (String s : list) {
System.out.println(s);
}