Observer, Command, other behavioral patterns, and a pattern cheat sheet

The last group is behavioral patterns. They are about how objects talk to each other and share work. This lesson covers Observer and Command in depth, then Chain of Responsibility, Iterator and Template Method, and ends with a cheat sheet of every pattern in this section. The examples are real, tested code from an online shop: an order service that notifies listeners, a text editor with undo, a request pipeline, and a paged list of orders.

1. Observer

Observer lets one object (the subject) tell many others (the observers) when something happens, without knowing who they are. When an order is placed, the shop must send an email, update stock and record analytics. If placeOrder called all three directly, it would need to change for every new reaction.

Instead, the order service knows only one interface, OrderListener. Anyone can subscribe:

// Observer: Defines the notification contract.
interface OrderListener {
    void onOrderPlaced(Order order);
}

// Event data published to all registered observers.
record Order(String orderId, String product, int quantity) {
}

// Subject / Publisher: Manages observers and notifies them.
class OrderService {

    private final List<OrderListener> listeners =
            new CopyOnWriteArrayList<>();

    void subscribe(OrderListener listener) {
        listeners.add(listener);
    }

    void unsubscribe(OrderListener listener) {
        listeners.remove(listener);
    }

    void placeOrder(Order order) {
        // Persist the order before notifying observers.
        System.out.println("Order placed: " + order.orderId());

        for (OrderListener listener : listeners) {
            listener.onOrderPlaced(order);
        }
    }
}

// Concrete Observer: Sends order confirmation email.
class EmailListener implements OrderListener {

    @Override
    public void onOrderPlaced(Order order) {
        System.out.println("Email sent for order: " + order.orderId());
    }
}

InventoryListener and AnalyticsListener are the same shape. Wiring and running it:

public static void main(String[] args) {

    OrderService orderService = new OrderService();

    OrderListener emailListener = new EmailListener();
    OrderListener inventoryListener = new InventoryListener();
    OrderListener analyticsListener = new AnalyticsListener();

    // Register observers.
    orderService.subscribe(emailListener);
    orderService.subscribe(inventoryListener);
    orderService.subscribe(analyticsListener);

    Order order = new Order("ORD-101", "IPHONE-16", 2);

    orderService.placeOrder(order);

    // Unregister an observer.
    orderService.unsubscribe(analyticsListener);

    System.out.println("\nPlacing another order:");

    orderService.placeOrder(
            new Order("ORD-102", "MACBOOK", 1)
    );
}
Order placed: ORD-101
Email sent for order: ORD-101
Stock updated for: IPHONE-16
Analytics recorded for: ORD-101

Placing another order:
Order placed: ORD-102
Email sent for order: ORD-102
Stock updated for: MACBOOK

After unsubscribe, analytics no longer hears about the second order. Three details of this code matter in an interview:

  • Order saved first. The service persists the order before it notifies. A listener must never see an order that does not exist.
  • CopyOnWriteArrayList. The loop works on a snapshot, so a listener can unsubscribe itself during a notification without a ConcurrentModificationException. Our test checks this. The cost is a copy on every subscribe, which is fine because subscribing is rare and notifying is frequent.
  • No error handling in the loop. If one listener throws, the listeners after it are skipped and placeOrder fails. Our test confirms it. In production, wrap each call in its own try / catch and log the error.

Notifications here are synchronous: they run on the caller's thread, so a slow listener slows the order. That leads to the choice in the next table.

1.1 Observer, Event Bus or Message Broker?

Observer (in memory) Event bus Message broker (Kafka, RabbitMQ)
Where One JVM One JVM, central dispatcher Across services
Coupling Subject holds the listeners Neither side knows the other Neither side knows the other
If a listener is slow or down Caller waits or fails Often async, events may be lost Message waits and is retried

Start with Observer. Move to a broker when listeners live in other services or must not lose events (the messaging lessons cover this).

2. Command

Command turns a request into an object. Once an action is an object, you can store it, queue it, log it, run it later, and undo it. Our example is a text editor. The editor (the receiver) does the real work: append adds text and deleteLast removes characters and returns what it removed. A command wraps one action with its undo:

// Command: Defines execute and undo operations.
interface Command {
    void execute();
    void undo();
}

// Concrete Command: Appends text and supports undo.
class AppendCommand implements Command {

    private final TextEditor editor;
    private final String value;

    AppendCommand(TextEditor editor, String value) {
        this.editor = editor;
        this.value = value;
    }

    @Override
    public void execute() {
        editor.append(value);
    }

    @Override
    public void undo() {
        editor.deleteLast(value.length());
    }
}

// Concrete Command: Deletes text and supports undo.
class DeleteCommand implements Command {

    private final TextEditor editor;
    private final int count;
    private String removed;

    DeleteCommand(TextEditor editor, int count) {
        this.editor = editor;
        this.count = count;
    }

    @Override
    public void execute() {
        removed = editor.deleteLast(count);
    }

    @Override
    public void undo() {
        editor.append(removed);
    }
}

Notice how each command remembers what it needs to undo itself. Appending undoes by deleting the same number of characters. Deleting must remember the text it removed, so removed is saved during execute(). The invoker keeps a stack of the commands that have run:

// Invoker: Executes commands and maintains undo history.
class CommandHistory {

    private final Deque<Command> done = new LinkedList<>();

    void run(Command command) {
        command.execute();
        done.push(command);
    }

    void undo() {
        if (!done.isEmpty()) {
            done.pop().undo();
        }
    }
}

public static void main(String[] args) {

    TextEditor editor = new TextEditor();
    CommandHistory history = new CommandHistory();

    history.run(new AppendCommand(editor, "Hello"));
    history.run(new AppendCommand(editor, " World"));

    System.out.println("After append: " + editor.content());

    history.run(new DeleteCommand(editor, 6));

    System.out.println("After delete: " + editor.content());

    history.undo();

    System.out.println("After undo delete: " + editor.content());

    history.undo();

    System.out.println("After undo append: " + editor.content());
}
After append: Hello World
After delete: Hello
After undo delete: Hello World
After undo append: Hello

Edge cases from our tests: asking to delete more characters than exist removes everything, and undo brings it back. Calling undo() on an empty history does nothing. The history has no limit and no redo. Both are common follow-up questions.

Command appears in text editors, job queues (each job is a command), transaction logs and macro recording. It is the base of the "undo" requirement in many LLD problems.

3. Chain of Responsibility

Chain of Responsibility passes a request along a line of handlers. Each handler either stops the request with an answer or passes it on. Web filters, middleware and approval flows are chains. Our API request goes through authentication, a rate limit, a size check, and finally the order handler. The base class stores the next handler and forwards by default:

// Immutable request passed through the handler chain.
record Request(String token, String body, int count) {
}

// Base handler maintains a reference to the next handler.
abstract class Handler {
    private Handler next;

    // Links the next handler and supports fluent chain construction.
    Handler linkWith(Handler next) {
        this.next = next;
        return next;
    }

    // Passes the request to the next handler.
    // If no handler exists, the request is considered successfully processed.
    protected String handle(Request r) {
        return next == null ? "200 OK" : next.handle(r);
    }
}

// Validates the authentication token.
class AuthHandler extends Handler {

    @Override
    protected String handle(Request r) {
        if (!"valid".equals(r.token()))
            return "401 Unauthorized";

        // Authentication successful; continue to the next handler.
        return super.handle(r);
    }
}

// Checks whether the request count exceeds the configured limit.
class RateLimitHandler extends Handler {
    private final int limit;

    RateLimitHandler(int limit) {
        this.limit = limit;
    }

    @Override
    protected String handle(Request r) {
        if (limit < r.count())
            return "429 Too Many Requests";

        // Rate limit not exceeded; continue processing.
        return super.handle(r);
    }
}

ValidationHandler (rejects a body over 500 characters) and OrderHandler (does the work) follow the same pattern. The chain is built with linkWith, which returns the handler it linked, so the calls read left to right:

public static void main(String[] args) {

    // Build the chain of responsibility.
    Handler chain = new AuthHandler();

    chain.linkWith(new RateLimitHandler(3))
            .linkWith(new ValidationHandler())
            .linkWith(new OrderHandler());

    // Submit the request to the first handler.
    String response = chain.handle(new Request(
            "90982b23-d49c-4a01-a443-195a04e643ca",
            "{\"customer_id\":\"C1\",\"items\":[{\"id\":\"P1\",\"qty\":2}],\"total\":39.98}",
            1
    ));

    System.out.println(response);
}

This prints 401 Unauthorized, and that is correct. The demo token is a UUID, and AuthHandler accepts only the string "valid", so the request stops at the first handler. With a valid token and a count of 1, the response is Order. Our tests cover the rules of each handler:

  • With a limit of 3, a count of 3 passes and 4 gets 429 Too Many Requests.
  • A body of 500 characters passes and 501 gets 400 Bad Request. A missing body passes.
  • The first failing handler wins. A request with a bad token and a huge body returns 401, not 400.
  • If no handler handles the request, the base class returns 200 OK.

Order is part of the design: cheap checks first, so a bad token is rejected before anything expensive runs. The pattern also makes adding a check a one-line change in the wiring.

4. Template Method and Iterator

Template Method fixes the steps of a workflow in a base class and lets subclasses fill in some of them. You have already seen it. In the creational lesson, NotificationService.sendMessage() is the fixed workflow: create a channel, then send. Only createChannel() is left to subclasses. So Factory Method is a template method whose open step creates an object. Use it when several classes share the same steps with small differences. Prefer Strategy when you want to swap behavior at run time, because inheritance is fixed at compile time.

Iterator lets you walk a collection without knowing how it is stored. In Java it is Iterable and Iterator, which is what for (x : list) uses. A custom iterator is useful when data is not in memory. Our orders come from a paged API, and the iterator fetches one page at a time, only when the loop needs more:

// Iterator that lazily fetches orders from the API.
class PagingIterator implements Iterator<Order> {

    private final OrderApi api;
    private final int pageSize;

    private int page;
    private int index = 0;
    private List<Order> buffer = List.of();
    private boolean finished;

    PagingIterator(OrderApi api, int pageSize) {
        this.api = api;
        this.pageSize = pageSize;
    }

    @Override
    public boolean hasNext() {

        // Fetch the next page when the current buffer is exhausted.
        while (index >= buffer.size() && !finished) {

            buffer = api.fetch(page++, pageSize);
            index = 0;

            // No more orders available.
            if (buffer.isEmpty()) {
                finished = true;
                break;
            }

            // A smaller page indicates the last page.
            if (buffer.size() < pageSize)
                finished = true;
        }

        return index < buffer.size();
    }

    @Override
    public Order next() {

        if (!hasNext())
            throw new NoSuchElementException();

        return buffer.get(index++);
    }
}

Using it looks like any other loop. AllOrders is the Iterable that creates a PagingIterator:

for (Order order : orders) {
    System.out.println("Processing order: " + order);
}

With a page size of 2 and pages of 2 and 1 orders, the loop prints three orders and calls the API exactly twice. The short page tells the iterator it is the last, so it skips one more fetch. If the last page is full, one extra call returns an empty page to confirm the end. Nothing is fetched until the loop starts, and hasNext() can be called many times without fetching again. Memory holds one page, so a million orders never sit in memory together.

4.1 Other Behavioral Patterns to Know by Name

Mediator puts the communication between many objects in one place, as an air traffic tower does for planes. Memento saves and restores an object's state, which is another way to build undo. Visitor adds operations to a set of classes without changing them. They are asked less often. Know the one-line idea of each.

5. Worked Example: An Order Request, End to End

The demos are separate programs, so this follows a request through their real classes as if they were wired together:

flowchart LR
    R[Request] --> A[AuthHandler]
    A --> L[RateLimitHandler]
    L --> V[ValidationHandler]
    V --> O[OrderHandler]
    O --> S[OrderService.placeOrder]
    S --> E[EmailListener]
    S --> I[InventoryListener]
    S --> N[AnalyticsListener]
  1. Chain. The request passes authentication, the rate limit and validation. A bad token or an oversized body stops here with 401 or 400, so the order code never runs.
  2. Observer. OrderHandler places the order. The service saves it, then tells the email, stock and analytics listeners. A new reaction is one new listener.
  3. Command. If the order is edited in an admin tool, each edit can be a command on a history, so the admin can undo the last change.
  4. Iterator. A report that lists all orders uses AllOrders and reads page by page.

6. Pattern Cheat Sheet

Pattern Use it when Example from this section
Factory MethodA subclass should choose which object to createNotificationService
Abstract FactoryObjects must come in matching familiesAwsCloudServiceFactory
BuilderMany fields, some optional, object must be validAlert.Builder
SingletonExactly one instance per JVMEnumSingleton
AdapterAn existing class has the wrong interfaceLegacyGatewayAdapter
FacadeMany classes need one simple entryOrderFacade
DecoratorAdd behavior, stackable, same interfaceCachingRateProvider
ProxyControl access or delay creationDocumentProxy
StrategySwap interchangeable rulesPercentageDiscount
StateBehavior depends on the current statePaidState
ObserverOne event, many independent reactionsOrderListener
CommandQueue, log or undo an actionAppendCommand
Chain of ResponsibilityA request passes through ordered checksAuthHandler
IteratorWalk a collection without knowing its layoutPagingIterator

In an interview, do not name a pattern first. Describe the problem, then say which pattern fits and what it costs.

7. Common Pitfalls

  • One failing listener breaks the rest. Our placeOrder has no per-listener try / catch. Add one and log the error.
  • Slow synchronous listeners. They hold up the caller. Use a thread pool or a broker for slow work, such as email.
  • Forgetting to unsubscribe. A long-lived subject holding listeners keeps them from garbage collection, which is a memory leak.
  • Observer order assumptions. Listeners run in subscription order here, but do not rely on it. Each should work on its own.
  • Undo that cannot restore. A command must save what it needs. DeleteCommand stores removed in execute(). Undo before execute would append null.
  • An unbounded history. The undo stack grows forever. Cap it, as real editors do.
  • A chain with the wrong order. An expensive step before the cheap checks wastes work. Put authentication and limits first.
  • A chain nobody ends. Our base class returns 200 OK when no handler answers. Decide whether silent success is right or an error is safer.
  • Iterators that fetch eagerly or twice. Keep hasNext() free of side effects beyond loading the next page.

8. Interview Questions This Lesson Prepares You For

  • How does Observer reduce coupling? The subject knows only the listener interface, not the classes behind it. New reactions need no change in the subject.
  • What happens if an observer throws? In our code the remaining observers are skipped and the caller fails. Catch and log each call separately so one bad listener does not affect the others.
  • Why CopyOnWriteArrayList? Iteration works on a snapshot, so listeners can subscribe or unsubscribe during a notification without errors, and several threads can notify safely.
  • How do you implement undo and redo? Each command has execute and undo. Keep two stacks. Running a command pushes it on the undo stack. Undo moves it to the redo stack. A new command clears the redo stack.
  • Command or Strategy? A strategy is a rule used inside one job. A command is a whole request that you can store, queue and undo.
  • Where does Chain of Responsibility appear in real systems? Servlet filters, Spring interceptors, middleware, and approval flows. Each step can end the request or pass it on.
  • Why is Template Method different from Strategy? Template Method uses inheritance: subclasses fill steps, fixed when the code is compiled. Strategy uses composition: you swap the object at run time.
  • Why use an iterator for a paged API? The caller writes one simple loop. The iterator fetches pages on demand, so memory stays small and no page is fetched before it is needed.