Skills101

AdvancedOOP Concepts · Lesson 11 of 16 · Updated ·

Observer, Strategy and Decorator in Java — Design Patterns With Runnable Code

The last lesson was about creating objects. This one is about how objects work together. Observer and Strategy are behavioural patterns (they organise how objects communicate and choose behaviour). Decorator is a structural pattern (it organises how objects are combined). All three replace long if-else chains and "edit this class every time" code with small classes that plug together.

1. Observer: tell everyone who is interested

Problem: when a placement drive is announced, several parts of the system must react — email students, post on the notice board, update the dashboard. If the PlacementCell class calls each of them directly, every new reaction means editing PlacementCell.

Observer solves this. The subject (PlacementCell) keeps a list of observers (listeners) that implement one interface. When something happens, it loops over the list and calls each one. The subject does not know or care what the observers do.

Observer pattern: PlacementCell keeps a list of DriveListener objects; announce() calls onDrive() on EmailAlert, NoticeBoard and Dashboard, which subscribed earlier

import java.util.*;

interface DriveListener {
    void onDrive(String company, int minCgpaTimes10);
}

class PlacementCell {
    private final List<DriveListener> listeners = new ArrayList<>();

    void subscribe(DriveListener l) { listeners.add(l); }
    void unsubscribe(DriveListener l) { listeners.remove(l); }

    void announce(String company, int minCgpaTimes10) {
        for (DriveListener l : listeners) l.onDrive(company, minCgpaTimes10);
    }
}

class EmailAlert implements DriveListener {
    public void onDrive(String company, int min) {
        System.out.println("Email: " + company + " drive, min CGPA " + (min / 10.0));
    }
}

class NoticeBoard implements DriveListener {
    public void onDrive(String company, int min) {
        System.out.println("Notice board: " + company.toUpperCase() + " IS HIRING");
    }
}

public class Main {
    public static void main(String[] args) {
        PlacementCell cell = new PlacementCell();
        EmailAlert email = new EmailAlert();
        cell.subscribe(email);
        cell.subscribe(new NoticeBoard());
        // a listener written as a lambda — DriveListener has one method
        cell.subscribe((company, min) -> System.out.println("Dashboard: +1 drive (" + company + ")"));

        cell.announce("Infosys", 65);
        cell.unsubscribe(email);
        System.out.println("-- after email unsubscribed --");
        cell.announce("TCS", 60);
    }
}
Email: Infosys drive, min CGPA 6.5
Notice board: INFOSYS IS HIRING
Dashboard: +1 drive (Infosys)
-- after email unsubscribed --
Notice board: TCS IS HIRING
Dashboard: +1 drive (TCS)

Adding an SMS alert later means writing one new class and one subscribe call. PlacementCell is never edited — the open/closed principle at work.

Where you see Observer in real code: button click listeners in GUIs, addEventListener in JavaScript, Spring's @EventListener, and message queues like Kafka (at a much bigger scale: publish–subscribe between services).

Watch out: observers that are never unsubscribed keep objects alive in the list (a memory leak), and one slow listener slows down announce() for everyone.

2. Strategy: swap the algorithm

Problem: a canteen app calculates the bill differently for students, staff and on festival days. One calculate() method with if (type == STUDENT) … else if … grows forever.

Strategy puts each algorithm in its own class behind a common interface. The context (Billing) holds a strategy and can switch it at runtime.

import java.util.*;

interface PricingStrategy {
    int finalPrice(int amount);
}

class RegularPricing implements PricingStrategy {
    public int finalPrice(int amount) { return amount; }
}

class StudentPricing implements PricingStrategy {
    public int finalPrice(int amount) { return amount - amount * 10 / 100; }   // 10% off
}

class FestivalPricing implements PricingStrategy {
    public int finalPrice(int amount) { return Math.max(0, amount - 50); }     // flat Rs 50 off
}

class Billing {
    private PricingStrategy strategy;
    Billing(PricingStrategy strategy) { this.strategy = strategy; }
    void setStrategy(PricingStrategy strategy) { this.strategy = strategy; }
    int bill(int amount) { return strategy.finalPrice(amount); }
}

public class Main {
    public static void main(String[] args) {
        Billing billing = new Billing(new RegularPricing());
        System.out.println("Regular:  " + billing.bill(240));
        billing.setStrategy(new StudentPricing());
        System.out.println("Student:  " + billing.bill(240));
        billing.setStrategy(new FestivalPricing());
        System.out.println("Festival: " + billing.bill(240));
        billing.setStrategy(amount -> amount / 2);   // a strategy as a lambda
        System.out.println("Half:     " + billing.bill(240));
    }
}
Regular:  240
Student:  216
Festival: 190
Half:     120

You already use Strategy in the JDK: Collections.sort(list, comparator) — the Comparator is the strategy that decides the order, and sort does not change when you pass a different one.

Strategy vs Observer: a strategy is one algorithm chosen to do a job and its result is used; observers are many listeners told that something happened.

3. Decorator: add features by wrapping

Problem: a coffee shop sells coffee with optional milk, extra shot and whipped cream. Writing subclasses for every combination (CoffeeWithMilk, CoffeeWithMilkAndCream, …) explodes: 3 add-ons already give 8 combinations.

Decorator wraps an object in another object of the same interface. Each wrapper adds a little behaviour and then delegates to the object inside. Wrappers can be stacked in any order and number.

Decorator pattern: a Coffee object wrapped by Milk, wrapped by ExtraShot; cost() calls pass inward and each layer adds its own price on the way out

interface Drink {
    String name();
    int cost();
}

class Coffee implements Drink {
    public String name() { return "Coffee"; }
    public int cost() { return 60; }
}

abstract class AddOn implements Drink {      // the decorator base: holds a Drink
    protected final Drink inner;
    AddOn(Drink inner) { this.inner = inner; }
}

class Milk extends AddOn {
    Milk(Drink inner) { super(inner); }
    public String name() { return inner.name() + " + milk"; }
    public int cost() { return inner.cost() + 15; }
}

class ExtraShot extends AddOn {
    ExtraShot(Drink inner) { super(inner); }
    public String name() { return inner.name() + " + extra shot"; }
    public int cost() { return inner.cost() + 25; }
}

public class Main {
    public static void main(String[] args) {
        Drink plain = new Coffee();
        Drink order = new ExtraShot(new Milk(new Coffee()));
        Drink strong = new ExtraShot(new ExtraShot(new Coffee()));
        for (Drink d : new Drink[]{plain, order, strong}) {
            System.out.println(d.name() + " = Rs " + d.cost());
        }
    }
}
Coffee = Rs 60
Coffee + milk + extra shot = Rs 100
Coffee + extra shot + extra shot = Rs 110

Two add-on classes give us every combination, including "double extra shot". The best-known Decorator in Java is the I/O library: new BufferedReader(new InputStreamReader(System.in)) — BufferedReader wraps a reader and adds buffering and readLine().

Decorator vs inheritance: inheritance adds behaviour at compile time to a whole class; a decorator adds it at runtime to one object, and you can combine decorators freely.

4. Telling them apart

PatternTypeOne-line ideaJDK / framework example
Observerbehaviouralone event, many listenersGUI listeners, Spring @EventListener
Strategybehaviouralpick one algorithm, swap it at runtimeComparator passed to sort
Decoratorstructuralwrap an object to add behaviour, same interfaceBufferedReader wrapping a Reader

A quick test in interviews: "Does the object notify others?" → Observer. "Does the object let you plug in how a calculation is done?" → Strategy. "Does one object wrap another of the same type to add something?" → Decorator.

Common mistakes

  • Calling Strategy "polymorphism" and stopping there — say what varies (the algorithm) and who chooses it (the context or the caller).
  • Forgetting to unsubscribe observers, which causes memory leaks in long-running apps.
  • Making a decorator that does not implement the same interface as what it wraps — then it cannot be stacked or used in place of the original.
  • Using a decorator when one simple if would do; patterns are worth it when the variations keep growing.

Quick recap

  • Observer: the subject keeps a list of listeners and calls them all when something happens; subscribe/unsubscribe at runtime.
  • Strategy: each algorithm is a class (or lambda) behind one interface; the context delegates to whichever is set.
  • Decorator: wrappers with the same interface add behaviour layer by layer, avoiding a subclass for every combination.
  • Lambdas make Observer and Strategy short in modern Java when the interface has one method.

Practice what you learned

📝 Quiz: Observer, Strategy and Decorator5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →