Behavioral Patterns Part 2: Command, Observer, Mediator, and Chain of Responsibility
Model requests as objects, broadcast domain events, coordinate object collaboration, and pass requests through layered handlers.
Inside this chapter
- Command Pattern
- Observer Pattern
- Mediator Pattern
- Chain of Responsibility
- Real-World Usage Snapshot
Series navigation
Study the chapters in order for the clearest path from first design principles to advanced Java architecture, framework usage, and interview-level pattern mastery. Use the navigation at the bottom of the page to move through the full tutorial smoothly.
Command Pattern
Command wraps a request as an object. This enables queuing, logging, retries, undo support, scheduling, and decoupled execution. Batch jobs, UI actions, workflow tasks, and job dispatchers often reflect command thinking.
interface Command {
void execute();
}
class CreateInvoiceCommand implements Command {
public void execute() {
System.out.println("Invoice created");
}
} Observer Pattern
Observer lets one object notify interested listeners when something happens. It is useful for event-driven design, UI updates, audit hooks, metrics, and integration triggers. In modern Java systems, domain events and messaging often play observer-like roles.
Mediator Pattern
Mediator centralizes communication between collaborating objects. Instead of each component calling many others directly, they communicate through a mediator. This reduces direct coupling and is valuable in UI controllers, workflow coordinators, and orchestration logic.
Chain of Responsibility
Chain of Responsibility passes a request through multiple handlers until one processes it or the chain completes. Servlet filters, Spring security chains, validation pipelines, and request processing middleware are familiar examples.
abstract class Handler {
private Handler next;
public Handler linkWith(Handler next) {
this.next = next;
return next;
}
public void handle(String request) {
process(request);
if (next != null) {
next.handle(request);
}
}
protected abstract void process(String request);
} Real-World Usage Snapshot
These patterns are the backbone of extensible enterprise systems. Security filters, notification pipelines, event publishing, scheduled jobs, audit handlers, and request processing frameworks all rely on variations of these ideas.