Java Behavioral Desigh Patterns

 

🟣 BEHAVIORAL PATTERNS

(How objects interact, communicate, and change behavior)

Behavioral patterns focus on:

  • Communication between objects

  • Delegation of responsibilities

  • Runtime behavior changes

They help reduce tight coupling and make workflows extensible.


🔟 Observer Pattern

What

Observer defines a one-to-many dependency between objects.
When the Subject changes state, all Observers are notified automatically.

Why

Without Observer:

  • Subject must directly call every dependent class

  • Tight coupling between publisher and subscribers

  • Adding a new listener requires modifying subject code

Observer promotes event-driven design.

When

Use Observer when:

  • Multiple objects depend on one object’s state

  • You want publish-subscribe behavior

Real-world examples:

  • UI event listeners

  • Stock price notifications

  • Kafka consumers

Full Java Program (with Client)

import java.util.*; interface Observer { void update(String message); } class Subscriber implements Observer { private final String name; Subscriber(String name) { this.name = name; } public void update(String message) { System.out.println(name + " received: " + message); } } class NewsAgency { private final List<Observer> observers = new ArrayList<>(); void subscribe(Observer o) { observers.add(o); } void publish(String news) { for (Observer o : observers) { o.update(news); } } } public class ObserverClient { public static void main(String[] args) { NewsAgency agency = new NewsAgency(); agency.subscribe(new Subscriber("Vinod")); agency.subscribe(new Subscriber("John")); agency.publish("Java 21 Released"); } }

1️⃣1️⃣ Strategy Pattern

What

Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.

Why

Without Strategy:

  • Large if-else or switch blocks

  • Adding a new algorithm requires modifying existing logic

  • Violates Open–Closed Principle

When

Use Strategy when:

  • Multiple ways exist to perform an operation

  • Algorithm must change at runtime

Real-world examples:

  • Payment methods

  • Compression algorithms

  • Sorting strategies

Full Java Program (with Client)

interface PaymentStrategy { void pay(int amount); } class CardPayment implements PaymentStrategy { public void pay(int amount) { System.out.println("Paid " + amount + " using CARD"); } } class UpiPayment implements PaymentStrategy { public void pay(int amount) { System.out.println("Paid " + amount + " using UPI"); } } class Checkout { private PaymentStrategy strategy; Checkout(PaymentStrategy strategy) { this.strategy = strategy; } void setStrategy(PaymentStrategy strategy) { this.strategy = strategy; } void pay(int amount) { strategy.pay(amount); } } public class StrategyClient { public static void main(String[] args) { Checkout checkout = new Checkout(new CardPayment()); checkout.pay(1000); checkout.setStrategy(new UpiPayment()); checkout.pay(500); } }

1️⃣2️⃣ Command Pattern

What

Command encapsulates a request as an object, allowing it to be queued, logged, or undone.

Why

Without Command:

  • Sender tightly coupled to receiver

  • No easy undo/redo

  • Hard to queue or schedule operations

When

Use Command when:

  • You need undo/redo functionality

  • UI actions trigger business logic

  • Operations must be queued or logged

Real-world examples:

  • Button clicks

  • Job queues

  • Transaction commands

Full Java Program (with Client)

interface Command { void execute(); } class Light { void on() { System.out.println("Light ON"); } } class LightOnCommand implements Command { private final Light light; LightOnCommand(Light light) { this.light = light; } public void execute() { light.on(); } } class RemoteControl { private Command command; void setCommand(Command command) { this.command = command; } void pressButton() { command.execute(); } } public class CommandClient { public static void main(String[] args) { Light light = new Light(); RemoteControl remote = new RemoteControl(); remote.setCommand(new LightOnCommand(light)); remote.pressButton(); } }

1️⃣3️⃣ State Pattern

What

State allows an object to change its behavior when its internal state changes, without if-else logic.

Why

Without State:

  • Large conditional blocks

  • Hard to add new states

  • Violates Open–Closed Principle

When

Use State when:

  • Object behavior depends on state

  • State transitions are well defined

Real-world examples:

  • Order lifecycle

  • ATM states

  • Traffic lights

Full Java Program (with Client)

interface State { void next(Context ctx); } class Context { private State state; Context(State state) { this.state = state; } void setState(State state) { this.state = state; } void next() { state.next(this); } } class NewState implements State { public void next(Context ctx) { System.out.println("Order Paid"); ctx.setState(new PaidState()); } } class PaidState implements State { public void next(Context ctx) { System.out.println("Order Shipped"); } } public class StateClient { public static void main(String[] args) { Context order = new Context(new NewState()); order.next(); order.next(); } }

1️⃣4️⃣ Chain of Responsibility Pattern

What

Chain of Responsibility passes a request through a chain of handlers until one handles it.

Why

Avoids:

  • Large if-else chains

  • Tight coupling between sender and receiver

When

Use Chain when:

  • Multiple handlers may process a request

  • Order of processing matters

Real-world examples:

  • Authentication filters

  • Logging pipelines

  • Validation chains

Full Java Program (with Client)

abstract class Handler { protected Handler next; Handler setNext(Handler next) { this.next = next; return next; } abstract void handle(); } class AuthHandler extends Handler { void handle() { System.out.println("Authentication passed"); if (next != null) next.handle(); } } class LogHandler extends Handler { void handle() { System.out.println("Request logged"); } } public class ChainClient { public static void main(String[] args) { new AuthHandler() .setNext(new LogHandler()) .handle(); } }

1️⃣5️⃣ Mediator Pattern

What

Mediator centralizes communication between objects so they don’t talk to each other directly.

Why

Without Mediator:

  • Objects become tightly coupled

  • Changes ripple across classes

When

Use Mediator when:

  • Many objects interact

  • Communication logic is complex

Real-world examples:

  • Chat rooms

  • UI component interaction

  • Air traffic control

Full Java Program (with Client)

class Mediator { void send(String message) { System.out.println(message); } } class User { private final String name; private final Mediator mediator; User(String name, Mediator mediator) { this.name = name; this.mediator = mediator; } void send(String msg) { mediator.send(name + ": " + msg); } } public class MediatorClient { public static void main(String[] args) { Mediator mediator = new Mediator(); new User("Vinod", mediator).send("Hello"); } }

1️⃣6️⃣ Memento Pattern

What

Memento captures and stores an object’s internal state so it can be restored later.

Why

Direct access to internal state breaks encapsulation.

When

Use Memento when:

  • Undo functionality is required

  • State rollback is needed

Real-world examples:

  • Text editors

  • Game save points

Full Java Program (with Client)

class Editor { private String text; static class Memento { private final String state; Memento(String state) { this.state = state; } } void setText(String text) { this.text = text; } String getText() { return text; } Memento save() { return new Memento(text); } void restore(Memento memento) { this.text = memento.state; } } public class MementoClient { public static void main(String[] args) { Editor editor = new Editor(); editor.setText("Version 1"); Editor.Memento backup = editor.save(); editor.setText("Version 2"); editor.restore(backup); System.out.println(editor.getText()); } }

1️⃣7️⃣ Iterator Pattern

What

Iterator provides a way to traverse a collection without exposing its internal structure.

Why

  • Prevents exposing internals

  • Provides uniform traversal

When

Use when:

  • Traversing collections

  • Uniform access required

Full Java Program (with Client)

import java.util.*; public class IteratorClient { public static void main(String[] args) { List<String> list = List.of("A", "B", "C"); Iterator<String> it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }

1️⃣8️⃣ Interpreter Pattern

What

Defines a grammar and interprets expressions of that grammar.

Why

Simplifies expression evaluation logic.

When

Use when:

  • Simple DSL required

  • Rule engines or expression evaluators

Full Java Program (with Client)

interface Expression { int interpret(); } class NumberExpr implements Expression { int value; NumberExpr(int value) { this.value = value; } public int interpret() { return value; } } class AddExpr implements Expression { Expression left, right; AddExpr(Expression left, Expression right) { this.left = left; this.right = right; } public int interpret() { return left.interpret() + right.interpret(); } } public class InterpreterClient { public static void main(String[] args) { Expression expr = new AddExpr(new NumberExpr(5), new NumberExpr(10)); System.out.println(expr.interpret()); } }

1️⃣9️⃣ Visitor Pattern

What

Visitor allows adding new operations to object structures without modifying them.

Why

Prevents bloated domain classes.

When

Use when:

  • Object structure is stable

  • Operations change frequently

Full Java Program (with Client)

interface Visitor { void visit(Book book); } interface Item { void accept(Visitor visitor); } class Book implements Item { int price = 500; public void accept(Visitor visitor) { visitor.visit(this); } } class PriceVisitor implements Visitor { public void visit(Book book) { System.out.println("Book price: " + book.price); } } public class VisitorClient { public static void main(String[] args) { new Book().accept(new PriceVisitor()); } }

No comments:

Post a Comment

Social Media Feed System Design (Timeline) — High Level

  Social Media Feed System Design (Timeline) — High Level 1) Use Case & Problem Context We need to serve a fresh, ranked timeline for...

Featured Posts