When you subscribe to a YouTube channel, you don't keep refreshing the channel page every five minutes. The channel notifies you when a new video is out. When you pay on a shopping site, the checkout doesn't care how the discount is calculated today — festive offer, coupon or none — it just applies whichever rule is plugged in. And when you press Ctrl+Z in a text editor, the editor somehow remembers each action as a "thing" it can reverse.
These are three classic behavioral patterns: Observer, Strategy and Command. As we saw in Introduction to Design Patterns, behavioral patterns deal with how objects communicate and how responsibilities are divided between them. All three turn something that is usually hard-coded — who gets informed, which algorithm runs, which action is performed — into objects that can be swapped at run time.
Observer Pattern
Observer defines a one-to-many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified and updated automatically.
The Problem
A live cricket match has a score that changes often. Many parts of the system care: the mobile app, a TV graphics feed, a "milestone alert" service, maybe a betting-odds engine later. If the match class calls each of them directly (app.show(...), tv.update(...)...), it depends on every one of them, and adding a new consumer means editing the match class.
The other option, every consumer asking "has the score changed?" in a loop (polling), wastes work and still reacts late.
The Solution
The subject keeps a list of objects that implement a small observer interface. Anyone can subscribe or unsubscribe. When the state changes, the subject loops over the list and calls each observer. The subject knows only the interface, never the concrete classes.
subscribe / unsubscribe
┌──────────────┐ ◀────────────────────── ┌──────────────────────────┐
│ LiveMatch │ │ «interface» ScoreListener│
│ (Subject) │ ── notifies all ──────▶ │ onScoreUpdate(...) │
│ listeners[] │ └────────────▲─────────────┘
└──────────────┘ ┌────────────┼────────────┐
MobileApp MilestoneAlert (lambda)import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
// Observer interface
interface ScoreListener {
void onScoreUpdate(String match, int runs, int wickets);
}
// Subject
class LiveMatch {
private final String name;
private final List<ScoreListener> listeners = new CopyOnWriteArrayList<>();
private int runs;
private int wickets;
LiveMatch(String name) {
this.name = name;
}
public void subscribe(ScoreListener l) { listeners.add(l); }
public void unsubscribe(ScoreListener l) { listeners.remove(l); }
public void scoreChanged(int runsAdded, boolean wicket) {
runs += runsAdded;
if (wicket) wickets++;
notifyListeners();
}
private void notifyListeners() {
for (ScoreListener l : listeners) {
l.onScoreUpdate(name, runs, wickets); // push model: the data is sent along
}
}
}
// Concrete observers
class MobileApp implements ScoreListener {
@Override
public void onScoreUpdate(String match, int runs, int wickets) {
System.out.println(" App: " + match + " " + runs + "/" + wickets);
}
}
class MilestoneAlert implements ScoreListener {
private boolean fiftyAnnounced = false;
@Override
public void onScoreUpdate(String match, int runs, int wickets) {
if (runs >= 50 && !fiftyAnnounced) {
fiftyAnnounced = true;
System.out.println(" ALERT: " + match + " reaches 50!");
}
}
}
class ObserverDemo {
public static void main(String[] args) {
LiveMatch match = new LiveMatch("IND vs AUS");
MobileApp app = new MobileApp();
match.subscribe(app);
match.subscribe(new MilestoneAlert());
match.subscribe((m, r, w) -> { // a lambda works too
if (w > 0) System.out.println(" TV: wicket count is " + w);
});
System.out.println("Update 1"); match.scoreChanged(46, false);
System.out.println("Update 2"); match.scoreChanged(6, false);
System.out.println("Update 3"); match.scoreChanged(3, true);
match.unsubscribe(app);
System.out.println("Update 4 (app unsubscribed)"); match.scoreChanged(9, false);
}
}Output:
Update 1
App: IND vs AUS 46/0
Update 2
App: IND vs AUS 52/0
ALERT: IND vs AUS reaches 50!
Update 3
App: IND vs AUS 55/1
TV: wicket count is 1
Update 4 (app unsubscribed)
TV: wicket count is 1Trace it:
Update 1: all three observers are called. Only the app prints; the alert waits for 50, the TV lambda waits for a wicket.
Update 2: the score crosses 50, so
MilestoneAlertfires once and remembers that it has done so.Update 4: the app has unsubscribed, so only the TV observer prints.
LiveMatch never mentions MobileApp or MilestoneAlert. Subject and observers are loosely coupled: we can add a new observer without touching the subject (Open/Closed Principle). Because ScoreListener has a single abstract method, it is a functional interface, so a lambda works as an observer too.
Push vs Pull
Push model | Pull model |
|---|---|
Subject sends the changed data in the call: | Subject only says "I changed" and passes itself: |
Simple for observers | Observers fetch only what they need |
Subject must guess what every observer needs | Observers depend on the subject's getters |
Our example uses push. Many real event systems pass a single event object (like ActionEvent or PropertyChangeEvent) that contains the changed data plus a reference to the source, which is a mix of both.
Practical Concerns
Thread safety and modification during notification. If an observer unsubscribes itself inside its callback while we are looping over an
ArrayList, the loop throwsConcurrentModificationException. We usedCopyOnWriteArrayList: iteration works on a snapshot, so adding/removing during notification (even from other threads) is safe. It suits observer lists, which are read often and changed rarely.Lapsed listener (memory leak). The subject holds strong references to its observers. If an observer is no longer needed but never unsubscribes, it can never be garbage-collected (see Object Lifecycle & Memory). Always unsubscribe when an observer's life ends.
Notification order should not be relied upon; observers should be independent.
Cascades: an observer that changes another subject can trigger long or even infinite update chains.
Observer in Java
Java once shipped java.util.Observable (a class) and java.util.Observer (an interface), but both have been deprecated since Java 9. Their event model was limited: Observable was a class, so your subject had to extend it, the notification order was unspecified, and the data passed was an untyped Object. Today you would write your own small interface as above, use java.beans.PropertyChangeSupport / PropertyChangeListener, or for asynchronous streams use reactive APIs (java.util.concurrent.Flow, RxJava, Project Reactor). GUI event listeners (addActionListener) and the publish–subscribe model of message brokers like Kafka are the same idea at different scales.
Observer is also the "model notifies the views" part of the MVC architecture.
Strategy Pattern
Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
The Problem
double payable(double total, String offer) {
if (offer.equals("FESTIVE")) {
return total * 0.80;
} else if (offer.equals("COUPON")) {
return total >= 500 ? total - 100 : total;
} else if (offer.equals("FLASH")) {
return total * 0.5;
}
return total;
}Every new offer means editing this method and retesting all the old branches. The method grows forever and violates both Single Responsibility and Open/Closed (SOLID: Single Responsibility & Open/Closed).
The Solution
Put each algorithm in its own class behind a common interface. The object that uses the algorithm (the context) holds a reference to a strategy and delegates to it.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
// Strategy interface
interface DiscountStrategy {
double apply(double amount);
}
// Concrete strategies
class NoDiscount implements DiscountStrategy {
public double apply(double amount) { return amount; }
}
class FestiveDiscount implements DiscountStrategy { // 20% off
public double apply(double amount) { return amount * 0.80; }
}
class FlatCoupon implements DiscountStrategy { // Rs 100 off on orders of Rs 500 or more
public double apply(double amount) { return amount >= 500 ? amount - 100 : amount; }
}
// Context
class Cart {
private final double total;
private DiscountStrategy strategy = new NoDiscount();
Cart(double total) { this.total = total; }
void setStrategy(DiscountStrategy strategy) { this.strategy = strategy; }
double payable() { return strategy.apply(total); }
}
class StrategyDemo {
public static void main(String[] args) {
Cart cart = new Cart(800);
System.out.println("No discount : " + cart.payable());
cart.setStrategy(new FestiveDiscount());
System.out.println("Festive : " + cart.payable());
cart.setStrategy(new FlatCoupon());
System.out.println("Coupon : " + cart.payable());
cart.setStrategy(amount -> amount * 0.5); // a new strategy as a lambda
System.out.println("Flash sale : " + cart.payable());
// The JDK uses Strategy too: Comparator is the strategy, sort() is the context
List<String> names = new ArrayList<>(List.of("Zoya", "Ankit", "Bhavya", "Om"));
names.sort(Comparator.naturalOrder());
System.out.println(names);
names.sort(Comparator.comparing(String::length));
System.out.println(names);
}
}Output:
No discount : 800.0
Festive : 640.0
Coupon : 700.0
Flash sale : 400.0
[Ankit, Bhavya, Om, Zoya]
[Om, Zoya, Ankit, Bhavya]Key observations:
Carthas noif-elseon offer types. It just callsstrategy.apply(total); polymorphism (Polymorphism) picks the right code.The strategy can be changed at run time with
setStrategy(). A new offer is a new class (or lambda) —Cartis never edited.Each strategy is small and can be unit-tested on its own.
Since Java 8, a one-method strategy interface is a functional interface, so simple strategies can be lambdas, like the flash sale.
Comparatoris the JDK's most famous strategy:sort()is the context, and you pass in the comparison algorithm. The same list was sorted alphabetically and then by length (2, 4, 5 and 6 letters) just by passing a different comparator.
Strategy vs Inheritance vs State
You could also create FestiveCart, CouponCart subclasses. But then one cart object can never switch offers, and if a cart also had a "delivery fee algorithm" you'd need a subclass per combination. Strategy is composition: "a cart has a discount strategy".
The State pattern has almost the same class diagram, but a different intent:
Strategy | State |
|---|---|
The client usually chooses and sets the algorithm | The object changes its own state as events happen (e.g. Order: Placed → Shipped → Delivered) |
Strategies are independent and don't know about each other | States often know which state comes next |
"How should this task be done?" | "How should I behave in my current state?" |
Command Pattern
Command encapsulates a request as an object, thereby letting you parameterise clients with different requests, queue or log requests, and support undoable operations.
The Idea
Normally a request is a method call that happens and is gone: editor.insert("Hello"). Command turns that call into an object that stores who should do the work (the receiver) and with what arguments. Once a request is an object, you can:
store it in a history and undo / redo it,
put it in a queue and run it later or on another thread,
log it, send it over a network, or replay it after a crash,
attach it to a button or menu item without the button knowing what it does.
A restaurant is a good analogy: the customer (client) gives an order to the waiter (invoker), who writes it on an order slip (command) and hands it to the kitchen. The cook (receiver) does the real work. The waiter doesn't know how to cook, and the slip can wait in a queue.
The Roles
Role | Responsibility | In our example |
|---|---|---|
Command | Interface with |
|
Concrete Command | Stores the receiver and arguments; calls the receiver |
|
Receiver | Knows how to do the actual work |
|
Invoker | Triggers commands; may keep history |
|
Client | Creates commands and wires them to receivers |
|
Example: Text Editor with Undo and Redo
import java.util.ArrayDeque;
import java.util.Deque;
// Receiver: knows how to do the real work
class TextEditor {
private final StringBuilder text = new StringBuilder();
void insert(String s) { text.append(s); }
void deleteLast(int n) { text.setLength(text.length() - n); }
String getText() { return text.toString(); }
}
// Command interface
interface EditCommand {
void execute();
void undo();
}
// Concrete commands: each stores its receiver and its arguments
class TypeCommand implements EditCommand {
private final TextEditor editor;
private final String words;
TypeCommand(TextEditor editor, String words) {
this.editor = editor;
this.words = words;
}
public void execute() { editor.insert(words); }
public void undo() { editor.deleteLast(words.length()); }
}
class DeleteCommand implements EditCommand {
private final TextEditor editor;
private final int count;
private String deleted = ""; // remembered so that undo can restore it
DeleteCommand(TextEditor editor, int count) {
this.editor = editor;
this.count = count;
}
public void execute() {
String t = editor.getText();
deleted = t.substring(t.length() - count);
editor.deleteLast(count);
}
public void undo() { editor.insert(deleted); }
}
// Invoker: runs commands and keeps history; knows nothing about TextEditor internals
class CommandManager {
private final Deque<EditCommand> undoStack = new ArrayDeque<>();
private final Deque<EditCommand> redoStack = new ArrayDeque<>();
void run(EditCommand c) {
c.execute();
undoStack.push(c);
redoStack.clear(); // a new action makes old redo history invalid
}
void undo() {
if (undoStack.isEmpty()) return;
EditCommand c = undoStack.pop();
c.undo();
redoStack.push(c);
}
void redo() {
if (redoStack.isEmpty()) return;
EditCommand c = redoStack.pop();
c.execute();
undoStack.push(c);
}
}
class CommandDemo {
public static void main(String[] args) {
TextEditor editor = new TextEditor();
CommandManager manager = new CommandManager();
manager.run(new TypeCommand(editor, "Hello"));
manager.run(new TypeCommand(editor, " World"));
System.out.println("Typed : " + editor.getText());
manager.run(new DeleteCommand(editor, 6));
System.out.println("Deleted 6 : " + editor.getText());
manager.undo();
System.out.println("Undo : " + editor.getText());
manager.undo();
System.out.println("Undo again : " + editor.getText());
manager.redo();
System.out.println("Redo : " + editor.getText());
}
}Output:
Typed : Hello World
Deleted 6 : Hello
Undo : Hello World
Undo again : Hello
Redo : Hello WorldTrace the two stacks:
Action Text undoStack (top first) redoStack
run Type "Hello" Hello [Type"Hello"] []
run Type " World" Hello World [Type" World", Type"Hello"] []
run Delete 6 Hello [Del6, Type" World", ...] []
undo Hello World [Type" World", Type"Hello"] [Del6]
undo Hello [Type"Hello"] [Type" World", Del6]
redo Hello World [Type" World", Type"Hello"] [Del6]Notice two important details:
DeleteCommandremembers what it deleted duringexecute(). Undo needs that information; a command that can be undone must store enough state to reverse itself.Running a new command clears the redo stack. After you type something new, the old "future" no longer makes sense — exactly how real editors behave.
Commands in a Queue: Runnable
Java's Runnable is a command interface with just execute() (called run()). Anything that accepts a Runnable — a thread, an executor, a scheduler — is an invoker that runs requests without knowing what they do.
import java.util.ArrayDeque;
import java.util.Queue;
class JobsDemo {
public static void main(String[] args) {
Queue<Runnable> jobs = new ArrayDeque<>(); // Runnable = a command with only execute()
jobs.add(() -> System.out.println("Send fee reminder emails"));
jobs.add(() -> System.out.println("Generate attendance report"));
jobs.add(() -> System.out.println("Back up the marks database"));
System.out.println(jobs.size() + " jobs queued, running them now:");
while (!jobs.isEmpty()) {
jobs.poll().run();
}
}
}Output:
3 jobs queued, running them now:
Send fee reminder emails
Generate attendance report
Back up the marks databaseThe jobs were created first and executed later, by code that only knows the Runnable interface. Submitting tasks to an ExecutorService is the same pattern with threads behind it.
Observer vs Strategy vs Command
Question | Observer | Strategy | Command |
|---|---|---|---|
What is turned into an object? | A dependent that wants to be informed | An algorithm | A request/action |
How many are active at once? | Many observers per subject | Usually one strategy per context | Many commands, often stored in history or a queue |
Main benefit | One-to-many notification, loose coupling | Swap algorithms at run time, no | Undo/redo, queuing, logging, decoupling invoker from receiver |
JDK example | Event listeners, |
|
|
Strategy and Command both wrap behaviour in an object and both can be lambdas in modern Java. The difference is intent: a strategy answers "how should this be done?" for a context that always does the same task; a command represents "what should be done", as a standalone request that can be stored, delayed or undone.
Common Mistakes
Never unsubscribing observers, causing memory leaks and "ghost" updates to screens that are already closed.
Iterating a plain
ArrayListof observers while observers may add/remove themselves, causingConcurrentModificationException.Using the deprecated
java.util.Observablein new code.A context that still contains
if (strategy instanceof FestiveDiscount)— that defeats the purpose of Strategy.Creating a Strategy class for an algorithm that will never change. A plain method is simpler.
Undo that doesn't store the previous state (e.g. a delete command that cannot restore what it deleted).
Forgetting to clear the redo stack after a new command.
Interview Questions
Explain the Observer pattern with a real example.
A subject maintains a list of observers and notifies all of them when its state changes. Example: a YouTube channel (subject) notifies subscribers (observers) when a new video is uploaded; in code, GUI buttons notify registered event listeners when clicked.
Why were java.util.Observer and Observable deprecated?
java.util.Observer and Observable deprecated?They were deprecated in Java 9. The JDK documentation explains that the event model is quite limited, the order of notifications is unspecified, and state changes don't correspond one-to-one with notifications. In addition, Observable is a class (so your subject must extend it) and the update data is an untyped Object. Alternatives are custom listener interfaces, java.beans property-change support, concurrent queues, and the java.util.concurrent.Flow reactive API.
How does the Strategy pattern support the Open/Closed Principle?
The context depends only on the strategy interface. New behaviour is added by writing a new strategy class (or lambda) without modifying the context or existing strategies, so the code is open for extension but closed for modification.
What is the difference between Strategy and State?
Both delegate behaviour to an interchangeable object. In Strategy the client normally chooses the algorithm and strategies are independent. In State, the object switches its own state object as its internal state changes, and states often decide the next state.
How would you implement undo/redo?
Use the Command pattern: every action is a command object with execute() and undo() that stores what it needs to reverse itself. Keep an undo stack and a redo stack: executing pushes onto undo and clears redo; undo pops from undo, calls undo() and pushes onto redo; redo does the reverse.
Which JDK interfaces represent Strategy and Command?
Comparator is a strategy for ordering, passed to sort(). Runnable and Callable are commands, executed later by threads or executors that don't know what they do.
Summary
Observer: a subject notifies a list of observers on change (one-to-many). Watch out for unsubscribing, thread-safe lists and notification cascades.
java.util.Observableis deprecated since Java 9.Strategy: a family of interchangeable algorithms behind one interface; the context delegates and can switch at run time.
Comparatoris the classic JDK strategy.Command: a request becomes an object (receiver + arguments), enabling undo/redo, queues and logging.
Runnableis a simple command.All three replace hard-coded calls or
if-elsechains with objects behind interfaces — composition and polymorphism doing the work.
Patterns are usually communicated through diagrams. In the next chapter, UML Class Diagrams, we will learn the standard notation for drawing classes and their relationships.