00:00

Behavioral Design Patterns in Java

Last updated:

Behavioral design patterns in Java are proven ways to divide responsibilities between objects and to organise how those objects communicate. Instead of one class deciding everything with long chains of conditions, each decision (validation, pricing, lifecycle rules, notifications) moves into a small object with a clear role, and the objects collaborate through interfaces.

They matter because behaviour is the part of an application that changes most often. New discount campaigns, new approval rules and new notification channels arrive every sprint. When all of that sits in a single service method, every change touches the same code and risks breaking unrelated rules. Behavioral patterns are one of the three Gang of Four (GoF) categories, next to creational and structural patterns.

1. What Are Behavioral Design Patterns?

The GoF book describes behavioral patterns as patterns concerned with algorithms and the assignment of responsibilities between objects. They describe not only objects and classes but also the patterns of communication between them.

Where creational patterns answer "how is this object made?" and structural patterns answer "how do these objects fit together?", behavioral patterns answer "who does what, and how do they talk?". Almost all of them use the same move: take a piece of behaviour that varies or must be coordinated, put it behind an interface, and let objects call each other through that interface.

Two flavours exist. Object behavioral patterns, the majority, use composition: one object holds and delegates to another, as Strategy and Observer do. Class behavioral patterns use inheritance to spread behaviour across a hierarchy, as Template Method and Interpreter do. In object-oriented terms, these patterns turn conditional logic into polymorphism and replace hard-wired calls with loose coupling, which follows the Single Responsibility and Open/Closed principles.

2. The 11 Behavioral Patterns at a Glance

PatternIn one sentenceTypical Java example
Chain of ResponsibilityPass a request along handlers until one handles it or one stops it.Servlet filters, Spring Security filter chain
CommandTurn a request into an object that can be queued, logged or undone.Runnable submitted to an executor
InterpreterRepresent a small language's grammar as classes and evaluate sentences.java.util.regex.Pattern, expression languages
IteratorWalk a collection without exposing how it is stored.Iterable and Iterator
MediatorLet objects talk through one coordinator instead of to each other.A checkout coordinator, chat rooms, UI dialogs
MementoCapture an object's state so it can be restored later.Editor snapshots, undo history
ObserverNotify all subscribers automatically when something changes.Spring @EventListener, Swing listeners
StateChange an object's behaviour when its internal state changes.Order and payment lifecycles, circuit breakers
StrategyMake algorithms interchangeable behind one interface.Comparator, PasswordEncoder
Template MethodFix an algorithm's outline and let subclasses fill in steps.AbstractList, HttpServlet.service()
VisitorAdd operations to a set of classes without changing them.java.nio.file.FileVisitor

Patterns with a dedicated tutorial on JavaByTechie are linked; each covers structure, three runnable examples and interview questions.

3. When Are Behavioral Patterns Useful?

  • Growing rule sets: pricing, validation or approval rules that change independently of each other.
  • Many interested parties: one event, such as "order placed", that several modules must react to.
  • Lifecycles and workflows: objects whose allowed actions depend on their status, or multi-step processes that need undo and retries.

4. UML Class Diagram

There is no single diagram for a whole category, so this one shows four behavioral patterns working inside one order service, taken from the code in section 8.

Behavioral patterns in one order service OrderService holds a list of OrderCheck handlers (Chain of Responsibility) and a list of OrderListener observers (Observer), uses a DiscountStrategy passed to placeOrder (Strategy), and changes the Order's OrderState (State). Chain of Responsibility «interface» OrderCheck + check(order): Optional Observer «interface» OrderListener + onPlaced(order, total) OrderService - checks: List<OrderCheck> - listeners: List<OrderListener> + placeOrder(order, discount) 0..* 0..* «interface» DiscountStrategy + apply(subtotal): BigDecimal Strategy uses Order - state: OrderState changes «enum» OrderState NEW, PLACED, CANCELLED + place(): OrderState State 1
Four behavioral patterns around one context: OrderService delegates validation, pricing, lifecycle and notifications to objects it reaches only through interfaces or the state enum.
  1. Chain of Responsibility: OrderService holds a list of OrderCheck handlers; any one can reject the order.
  2. Strategy: a DiscountStrategy is passed into placeOrder() (dashed dependency), so pricing varies per call.
  3. State: each Order holds one OrderState, and the enum constant decides whether place() is allowed.
  4. Observer: the service holds any number of OrderListeners and notifies all of them after success.

5. Step-by-Step Execution Flow

  1. At startup, the application builds OrderService with its checks and subscribes the listeners (email, SMS, loyalty).
  2. A request calls placeOrder(order, tenPercent).
  3. The service runs each OrderCheck in order; the first rejection ends the request (Chain of Responsibility).
  4. It calls discount.apply(subtotal) to price the order (Strategy).
  5. It asks the order's current state for the next one with state.place(); PLACED refuses a second placement (State).
  6. It loops over the listeners and calls onPlaced() on each (Observer), then returns the result.

No object knows the concrete classes of the others: every collaboration goes through an interface or the enum.

6. Real-World Use Cases

  • E-commerce: discount and shipping strategies, order lifecycles as state machines, "order placed" events with many observers.
  • Payments and banking: validation and fraud chains, payment state machines, queued standing instructions as commands, statement exports as template methods.
  • Notifications: observers per channel, retry policies as strategies, delivery tracking as states.
  • The JDK: Comparator (Strategy), Iterator, Runnable and Callable (Command), AbstractList (Template Method), java.nio.file.FileVisitor with Files.walkFileTree() (Visitor), and java.util.concurrent.Flow (Observer with backpressure).
  • Spring: ApplicationEventPublisher with @EventListener (Observer), the servlet and Spring Security filter chains (Chain of Responsibility), JdbcTemplate and TransactionTemplate callbacks (a callback form of Template Method), and interchangeable PasswordEncoder beans (Strategy).

7. Problem Without Behavioral Patterns

One method that validates, prices, enforces the lifecycle and notifies:

OrderServiceMonolith.java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class OrderServiceMonolith {

    static final class Order {
        final String id;
        final BigDecimal subtotal;
        final int quantity;
        String status = "NEW";

        Order(String id, String subtotal, int quantity) {
            this.id = id;
            this.subtotal = new BigDecimal(subtotal);
            this.quantity = quantity;
        }
    }

    // One method decides validation, pricing, lifecycle and notifications
    static String placeOrder(Order order, String campaign) {
        if (order.quantity > 5) return order.id + " rejected: max 5 per order";               // validation rule 1
        if (order.subtotal.compareTo(new BigDecimal("200000")) > 0) return order.id + " rejected: limit"; // rule 2

        BigDecimal total;                                                                      // pricing rules
        if (campaign.equals("PERCENT_10")) total = order.subtotal.multiply(new BigDecimal("0.90"));
        else if (campaign.equals("FLAT_500")) total = order.subtotal.subtract(new BigDecimal("500"));
        else total = order.subtotal;

        if (!order.status.equals("NEW")) return order.id + " rejected: already " + order.status;   // lifecycle rule
        order.status = "PLACED";

        System.out.println("  email: order " + order.id + " confirmed");                       // notifications
        System.out.println("  sms: order " + order.id + " confirmed");
        return order.id + " placed, total Rs. " + total.setScale(2, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) {
        Order order = new Order("ORD-1", "4000.00", 2);
        System.out.println(placeOrder(order, "PERCENT_10"));
        System.out.println(placeOrder(order, "PERCENT_10"));     // placing the same order twice
        System.out.println(placeOrder(new Order("ORD-2", "900.00", 9), "NONE"));
    }
}
Console
  email: order ORD-1 confirmed
  sms: order ORD-1 confirmed
ORD-1 placed, total Rs. 3600.00
ORD-1 rejected: already PLACED
ORD-2 rejected: max 5 per order
  • Four reasons to change in one method: risk, marketing, operations and CRM all edit it.
  • String-based choices: a typo in a campaign or status name compiles happily.
  • Hard-wired calls: adding loyalty points means editing checkout again.
  • Hard to test any single rule without running all the others.

8. Behavioral Design Patterns in Java: The Solution

Give each concern its own pattern: validation becomes a chain of checks, pricing a strategy, the lifecycle a state enum, and notifications a list of observers. The service only coordinates them.

BehavioralPatternsTogether.java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;

public class BehavioralPatternsTogether {

    static final class Order {
        final String id;
        final BigDecimal subtotal;
        final int quantity;
        OrderState state = OrderState.NEW;

        Order(String id, String subtotal, int quantity) {
            this.id = id;
            this.subtotal = new BigDecimal(subtotal);
            this.quantity = quantity;
        }
    }

    // Chain of Responsibility: each check may stop the order
    interface OrderCheck { Optional<String> check(Order order); }

    // Strategy: interchangeable pricing rules
    interface DiscountStrategy { BigDecimal apply(BigDecimal subtotal); }

    // State: the lifecycle decides which transitions are allowed
    enum OrderState {
        NEW { OrderState place() { return PLACED; } },
        PLACED,
        CANCELLED;

        OrderState place() { throw new IllegalStateException("already " + name()); }
    }

    // Observer: anyone interested in placed orders
    interface OrderListener { void onPlaced(Order order, BigDecimal total); }

    // Context: coordinates the four behaviours without knowing their implementations
    static final class OrderService {
        private final List<OrderCheck> checks;
        private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();

        OrderService(List<OrderCheck> checks) { this.checks = List.copyOf(checks); }

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

        String placeOrder(Order order, DiscountStrategy discount) {
            for (OrderCheck check : checks) {
                Optional<String> problem = check.check(order);
                if (problem.isPresent()) return order.id + " rejected: " + problem.get();
            }
            BigDecimal total = discount.apply(order.subtotal).setScale(2, RoundingMode.HALF_UP);
            try {
                order.state = order.state.place();
            } catch (IllegalStateException e) {
                return order.id + " rejected: " + e.getMessage();
            }
            listeners.forEach(listener -> listener.onPlaced(order, total));
            return order.id + " placed, total Rs. " + total;
        }
    }

    public static void main(String[] args) {
        OrderService service = new OrderService(List.of(
                order -> order.quantity > 5 ? Optional.of("max 5 per order") : Optional.empty(),
                order -> order.subtotal.compareTo(new BigDecimal("200000")) > 0 ? Optional.of("limit") : Optional.empty()));

        service.subscribe((order, total) -> System.out.println("  email: order " + order.id + " confirmed"));
        service.subscribe((order, total) -> System.out.println("  sms: order " + order.id + " confirmed"));
        service.subscribe((order, total) -> System.out.println("  loyalty: +" + total.intValue() / 100 + " points"));   // new, no service change

        DiscountStrategy tenPercent = subtotal -> subtotal.multiply(new BigDecimal("0.90"));
        DiscountStrategy none = subtotal -> subtotal;

        Order order = new Order("ORD-1", "4000.00", 2);
        System.out.println(service.placeOrder(order, tenPercent));
        System.out.println(service.placeOrder(order, tenPercent));
        System.out.println(service.placeOrder(new Order("ORD-2", "900.00", 9), none));
    }
}
Console
  email: order ORD-1 confirmed
  sms: order ORD-1 confirmed
  loyalty: +36 points
ORD-1 placed, total Rs. 3600.00
ORD-1 rejected: already PLACED
ORD-2 rejected: max 5 per order

The results match the original, but each rule now lives in one small, testable place. The loyalty listener was added without touching OrderService, new checks and campaigns are new lambdas or classes, and the enum makes illegal transitions impossible to express by accident. The program runs on Java 21 with java BehavioralPatternsTogether.java.

9. Best Practices and Common Mistakes

Best practices

  • Start from the problem: name the kind of change you expect, then pick the pattern that isolates it.
  • Keep behaviour interfaces small, ideally one method, so lambdas can implement them.
  • Wire collaborators through constructors or dependency injection, not with new inside the context.
  • Thread safety: shared handlers, strategies and observers should be stateless or immutable; use concurrent collections for listener lists and atomic operations for state transitions.

Common mistakes

  • Pattern-first design: adding Visitor or Mediator before any real need appears.
  • Moving conditionals instead of removing them, such as choosing strategies with a large switch in every caller.
  • Hidden control flow: chains and observers without logging, which makes "who handled this?" impossible to answer.
  • Ignoring failure paths: one listener's exception stopping the others, or a chain with no defined end.

10. When to Use and When Not to Use

Use them when a class has several independent reasons to change, when behaviour must be selected or reconfigured at runtime, or when different teams own different rules within one flow.

Avoid them when the logic is short and stable, when only one variant will ever exist, or when the extra indirection would make a simple flow harder to follow. A clear switch expression over an enum is often the better choice for two or three fixed cases.

11. Advantages and Disadvantages

Advantages

  • Loose coupling between the objects that trigger behaviour and those that implement it.
  • Open/Closed extension: new rules, handlers and listeners without editing existing code.
  • Small, focused, testable classes.
  • Runtime flexibility: behaviour can be swapped, queued, undone or extended.

Disadvantages

  • More types and indirection to navigate.
  • Harder debugging when control passes through chains and events.
  • Risk of overengineering for simple, stable logic.

12. Comparison with Other Categories and Similar Patterns

AspectCreationalStructuralBehavioral
Main questionHow are objects created?How are objects composed?How do objects share work and communicate?
FocusInstantiationRelationships and interfacesAlgorithms and responsibilities
ExamplesFactory, Builder, SingletonAdapter, Decorator, ProxyStrategy, Observer, State

Within the category, several pairs are easy to confuse. Strategy and State share a structure, but a client picks a strategy, while states switch themselves. Strategy and Template Method both vary an algorithm, but Strategy uses composition and Template Method uses inheritance. Observer and Mediator both decouple senders and receivers, but observers broadcast to everyone, while a mediator coordinates who talks to whom. Chain of Responsibility and Command often work together: commands are the requests passed along a chain.

13. Summary

  • Behavioral design patterns in Java define how objects share responsibilities and communicate.
  • Purpose: replace sprawling conditionals and hard-wired calls with small, collaborating objects.
  • The category has 11 GoF patterns, from Strategy and Observer to Visitor and Memento.
  • Most work by putting variable behaviour behind an interface and delegating to it.
  • Used for pricing rules, validation chains, lifecycles, events, undo and traversal.
  • Benefits: loose coupling, easy extension and focused tests.
  • Choose a pattern for a real, expected change, and keep shared behaviour objects thread-safe.

14. Java Design Pattern Interview Questions and Answers

Q1. What distinguishes behavioral patterns from creational and structural patterns?

Creational patterns control how objects are created, and structural patterns control how classes and objects are composed. Behavioral patterns control how responsibilities are assigned and how objects communicate at runtime, such as who handles a request or who is notified of a change.

Q2. Which behavioral patterns are class-based and which are object-based?

Template Method and Interpreter are class behavioral patterns: they rely on inheritance. The other nine (Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy, Visitor) are object behavioral patterns that rely on composition and delegation.

Q3. How do Java 8+ lambdas change the way behavioral patterns are written?

Many behavioral patterns revolve around single-method interfaces, which are functional interfaces. Strategies, commands, observers and chain handlers can then be written as lambdas or method references instead of named classes, which removes boilerplate while keeping the pattern's structure.

Comparator<Product> byPrice = Comparator.comparingInt(Product::price);   // Strategy
executor.submit(() -> ledger.post(entry));                             // Command
Q4. A colleague replaced a 3-case switch with Strategy classes. Is that always an improvement?

Not always. For a small, stable set of cases, an exhaustive switch expression over an enum is clearer and the compiler checks completeness. Strategy pays off when cases change often, are selected at runtime, carry their own dependencies, or are owned by different teams.

Q5. Strategy and State have the same class diagram. How do you tell them apart?

By who changes the behaviour. The client chooses a strategy, which usually stays fixed for that object; states replace themselves as events occur, so the object's behaviour changes over its lifetime. State objects typically know about other states; strategies are independent.

Q6. How do Observer and Mediator differ?

An observer subject broadcasts the same notification to every subscriber and does not decide who reacts. A mediator holds coordination logic and decides which colleagues to call and in what order. Use Observer for open-ended reactions to an event, and Mediator when the interactions themselves are complex rules.

Q7. How does the Memento pattern support undo without breaking encapsulation?

The originator creates a memento object containing a snapshot of its own state, and only the originator can read it back. A caretaker, such as an undo stack, stores mementos without looking inside them. A Java record nested in the originator, with private access, is a clean way to implement it.

Q8. Where does the JDK use the Visitor pattern?

java.nio.file.FileVisitor (and SimpleFileVisitor) is visited by Files.walkFileTree(), with callbacks for directories and files. The javax.lang.model API used by annotation processors also provides ElementVisitor and TypeVisitor.

Q9. Can Java 21 sealed interfaces and pattern matching replace the Visitor pattern?

Often, yes. With a sealed hierarchy, a switch with type patterns must be exhaustive, so adding a new subtype produces compile errors where it is not handled, which is the main safety Visitor provided. Visitor still helps when operations must be pluggable from outside the hierarchy's module.

BigDecimal fee(Payment p) {
    return switch (p) {            // Payment is sealed: Card, Upi, NetBanking
        case Card c -> c.amount().multiply(new BigDecimal("0.02"));
        case Upi u -> BigDecimal.ZERO;
        case NetBanking n -> new BigDecimal("15");
    };
}
Q10. Give a real example of the Interpreter pattern in Java.

java.util.regex.Pattern compiles a regular expression into an internal tree of node objects and evaluates input against it, which is the Interpreter idea. In application code, the pattern fits small rule languages, such as "amount > 5000 AND country = IN", parsed into expression objects with an evaluate(context) method.

Q11. Which behavioral patterns does Spring Framework use?

Observer through ApplicationEventPublisher and @EventListener; Chain of Responsibility through servlet filters, Spring Security's filter chain and HandlerInterceptors; Template Method through AbstractApplicationContext.refresh() hooks; and a callback-based template style in JdbcTemplate and TransactionTemplate. Strategy appears in interchangeable beans such as PasswordEncoder.

Q12. Why are shared behaviour objects a common source of concurrency bugs?

Strategies, handlers and listeners are usually singletons shared by all request threads. Any mutable field, such as a counter or cached request data, can be corrupted by concurrent access. Keep them stateless, pass per-request data as parameters, and use atomic or concurrent types for shared counters.

Q13. How do you stop one failing observer from breaking the others?

Wrap each listener call in its own try/catch, log the failure and continue the loop, or dispatch listeners asynchronously so failures are isolated. Spring's synchronous @EventListener calls propagate exceptions to the publisher, so wrap risky listeners or make them @Async.

Q14. When should events use @TransactionalEventListener instead of @EventListener?

When the reaction, such as sending an email, must only happen if the database transaction commits. @TransactionalEventListener runs by default in the AFTER_COMMIT phase, so a rolled-back order sends nothing. For guaranteed delivery across crashes, combine it with an outbox table.

Q15. Two webhook threads try to move the same payment to CAPTURED. How does the State pattern help, and what else is needed?

The State pattern defines that CAPTURED cannot be captured again, but concurrent threads can both read AUTHORIZED first. Make the transition atomic: AtomicReference.compareAndSet() in memory, or a conditional update or @Version optimistic lock in the database, so only one thread succeeds.

Q16. How would you implement undo for a shopping cart?

Represent each change as a Command with execute() and undo(), and keep executed commands on a stack. When a reverse operation is hard to write, store a Memento snapshot of the cart before executing and restore it on undo. Bound the history so it cannot grow without limit.

Q17. What is the Hollywood Principle and which patterns follow it?

"Don't call us, we'll call you": a framework or base class calls your code at the right time instead of your code driving the flow. Template Method follows it, since the base class calls subclass steps, and so do Observer callbacks and the framework hooks in Spring and servlet containers.

Q18. How do behavioral patterns appear in microservice architectures?

Publish-subscribe through Kafka or RabbitMQ is Observer across services. Sagas chain local transactions with compensating commands, so Command applies at the system level. API gateways run requests through filter chains, and circuit breakers are state machines with closed, open and half-open states.

Q19. How do you choose between Chain of Responsibility and a simple list of validators?

A list of validators that the service loops over is already a lightweight form of the pipeline variant, and it is often all you need. Use a linked chain with explicit "next" handlers when handlers must run code after the rest of the chain, decide to pass on modified requests, or be composed dynamically per request.

Q20. How do you explain the value of a behavioral pattern in a design interview without sounding like you are pattern-matching?

Describe the change you expect first ("marketing adds a campaign every month"), then the cost without structure (edits to one shared method and regressions), and only then name the pattern that isolates that change. Mention its cost too, such as extra classes or indirection, and when you would not use it.