Skip to main content

Lesson 4 of 6

Behavioural Patterns - Strategy, Observer, Command

Behavioural patterns define how objects communicate and share responsibility. Strategy encapsulates algorithms. Observer decouples event producers from consumers. Command encapsulates requests as objects (enable undo, logging, queuing).

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Strategy, Observer & Command

Strategy, Observer & Command
// ─── Strategy ────────────────────────────────────────────────
// Encapsulate a family of algorithms; make them interchangeable.
// (Already touched on - here with Lambda implementation)

@FunctionalInterface
interface SearchStrategy { List<Book> search(String query, List<Book> catalog); }

// Each strategy as a lambda - no class needed!
SearchStrategy byTitle  = (q, books) -> books.stream()
    .filter(b -> b.getTitle().toLowerCase().contains(q.toLowerCase()))
    .toList();

SearchStrategy byAuthor = (q, books) -> books.stream()
    .filter(b -> b.getAuthor().toLowerCase().contains(q.toLowerCase()))
    .toList();

SearchStrategy byIsbn   = (q, books) -> books.stream()
    .filter(b -> b.getIsbn().equals(q))
    .toList();

class SearchService {
    public List<Book> search(String query, String type, List<Book> catalog) {
        SearchStrategy strategy = switch (type) {
            case "title"  -> byTitle;
            case "author" -> byAuthor;
            case "isbn"   -> byIsbn;
            default -> throw new IllegalArgumentException("Unknown search type: " + type);
        };
        return strategy.search(query, catalog);
    }
}

// ─── Observer ─────────────────────────────────────────────────
// Define one-to-many dependency so all dependents are notified on state change.

// Event + Observer interfaces
public enum LibraryEvent { BOOK_ADDED, BOOK_BORROWED, BOOK_RETURNED, MEMBER_REGISTERED }
public interface LibraryObserver { void onEvent(LibraryEvent event, Object data); }

// Subject (Publisher)
public class LibrarySubject {
    private final Map<LibraryEvent, List<LibraryObserver>> listeners = new EnumMap<>(LibraryEvent.class);

    public void subscribe(LibraryEvent event, LibraryObserver observer) {
        listeners.computeIfAbsent(event, e -> new ArrayList<>()).add(observer);
    }

    public void unsubscribe(LibraryEvent event, LibraryObserver observer) {
        listeners.getOrDefault(event, List.of()).remove(observer);
    }

    protected void emit(LibraryEvent event, Object data) {
        listeners.getOrDefault(event, List.of())
                 .forEach(obs -> obs.onEvent(event, data));
    }
}

// Concrete observers - decoupled from each other
class AuditLogger implements LibraryObserver {
    public void onEvent(LibraryEvent e, Object data) {
        System.out.printf("[AUDIT] %s: %s%n", e, data);
    }
}

class EmailService implements LibraryObserver {
    public void onEvent(LibraryEvent e, Object data) {
        if (e == LibraryEvent.BOOK_BORROWED)
            System.out.println("📧 Borrow confirmation sent for: " + data);
    }
}

// ─── Command ──────────────────────────────────────────────────
// Encapsulate a request as an object. Supports undo, queuing, logging.

interface Command { void execute(); void undo(); }

class BorrowCommand implements Command {
    private final Book book;
    private final String memberId;
    private boolean executed = false;

    BorrowCommand(Book book, String memberId) { this.book = book; this.memberId = memberId; }

    public void execute() {
        if (!book.isAvailable()) throw new IllegalStateException("Book unavailable");
        book.borrow();
        executed = true;
        System.out.println("Borrowed: " + book.getTitle() + " by " + memberId);
    }

    public void undo() {
        if (executed) {
            book.returnItem();
            executed = false;
            System.out.println("Undo borrow: " + book.getTitle());
        }
    }
}

// CommandHistory - undo/redo stack
class CommandHistory {
    private final Deque<Command> history = new ArrayDeque<>();

    public void execute(Command cmd) {
        cmd.execute();
        history.push(cmd);  // save for undo
    }

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

Quick Quiz

Tip

Tip

Practice Behavioural Patterns Strategy Observer Command in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Behavioural Patterns - Strategy, Observer, Command

Practice Task

Note

Practice Task - (1) Write a working example of Behavioural Patterns Strategy Observer Command from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Behavioural Patterns Strategy Observer Command is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/6 done