Behavioral design patterns focus on how objects and classes interact and communicate with each other. They deal with the responsibilities of objects and the delegation of tasks among them. These patterns help you define clear and efficient ways for objects to collaborate while keeping your codebase flexible and maintainable.

Chain of Responsibility Pattern

The Chain of Responsibility Pattern passes a request along a chain of handlers. Each handler decides either to process the request or to pass it to the next handler in the chain.

Example

// Handler interface
abstract class Handler {
    protected Handler successor;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    public abstract void handleRequest(Request request);
}

// Request class
class Request {
    private String requestType;
    private String requestDescription;

    public Request(String requestType, String requestDescription) {
        this.requestType = requestType;
        this.requestDescription = requestDescription;
    }

    public String getRequestType() {
        return requestType;
    }

    public String getRequestDescription() {
        return requestDescription;
    }
}

// Concrete Handlers
class Clerk extends Handler {
    @Override
    public void handleRequest(Request request) {
        if (request.getRequestType().equalsIgnoreCase("Leave")) {
            System.out.println("Clerk: Approving leave request - " + request.getRequestDescription());
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

class Supervisor extends Handler {
    @Override
    public void handleRequest(Request request) {
        if (request.getRequestType().equalsIgnoreCase("Purchase")) {
            System.out.println("Supervisor: Approving purchase request - " + request.getRequestDescription());
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

class Manager extends Handler {
    @Override
    public void handleRequest(Request request) {
        if (request.getRequestType().equalsIgnoreCase("Raise Salary")) {
            System.out.println("Manager: Approving salary raise request - " + request.getRequestDescription());
        } else {
            System.out.println("Manager: Cannot handle this request.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Handler clerk = new Clerk();
        Handler supervisor = new Supervisor();
        Handler manager = new Manager();

        clerk.setSuccessor(supervisor);
        supervisor.setSuccessor(manager);

        Request request1 = new Request("Leave", "2 days leave");
        Request request2 = new Request("Purchase", "Office supplies");
        Request request3 = new Request("Raise Salary", "Employee X");

        clerk.handleRequest(request1);
        clerk.handleRequest(request2);
        clerk.handleRequest(request3);
    }
}

Command Pattern

The Command Pattern encapsulates a request as an object, thereby allowing you to parameterize clients with queues, requests, and operations. It also enables undoable operations and transactional behavior.

Example

// Receiver
class Light {
    void turnOn() {
        System.out.println("Light is on");
    }

    void turnOff() {
        System.out.println("Light is off");
    }
}

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

// Concrete Commands
class TurnOnLightCommand implements Command {
    private Light light;

    public TurnOnLightCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }
}

class TurnOffLightCommand implements Command {
    private Light light;

    public TurnOffLightCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOff();
    }
}

// Invoker
class RemoteControl {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void pressButton() {
        command.execute();
    }
}

public class Main {
    public static void main(String[] args) {
        Light livingRoomLight = new Light();
        Command turnOnCommand = new TurnOnLightCommand(livingRoomLight);
        Command turnOffCommand = new TurnOffLightCommand(livingRoomLight);

        RemoteControl remoteControl = new RemoteControl();

        remoteControl.setCommand(turnOnCommand);
        remoteControl.pressButton();

        remoteControl.setCommand(turnOffCommand);
        remoteControl.pressButton();
    }
}

Interpreter Pattern

The Interpreter Pattern is used to define a grammar for interpreting a language and provides a way to evaluate expressions in the language.

Example

// Context
class Context {
    private String input;
    private int output;

    public Context(String input) {
        this.input = input;
    }

    public String getInput() {
        return input;
    }

    public void setOutput(int output) {
        this.output = output;
    }

    public int getOutput() {
        return output;
    }
}

// Abstract Expression
interface Expression {
    void interpret(Context context);
}

// Terminal Expression
class NumberExpression implements Expression {
    private int number;

    public NumberExpression(int number) {
        this.number = number;
    }

    @Override
    public void interpret(Context context) {
        context.setOutput(number);
    }
}

// Non-terminal Expression
class AddExpression implements Expression {
    private Expression left;
    private Expression right;

    public AddExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public void interpret(Context context) {
        left.interpret(context);
        int leftValue = context.getOutput();
        right.interpret(context);
        int rightValue = context.getOutput();
        context.setOutput(leftValue + rightValue);
    }
}

public class Main {
    public static void main(String[] args) {
        // Example: 1 + 2
        Context context = new Context("1 + 2");
        Expression expression = parseExpression(context.getInput());
        expression.interpret(context);
        System.out.println("Result: " + context.getOutput());
    }

    private static Expression parseExpression(String input) {
        String[] tokens = input.split(" ");
        Expression left = new NumberExpression(Integer.parseInt(tokens[0]));
        Expression right = new NumberExpression(Integer.parseInt(tokens[2]));
        return new AddExpression(left, right);
    }
}

Iterator Pattern

The Iterator Pattern provides a way to access elements of an aggregate object sequentially without exposing the underlying representation.

Example

import java.util.ArrayList;
import java.util.List;

// Iterator interface
interface Iterator<T> {
    boolean hasNext();
    T next();
}

// Aggregate interface
interface Container<T> {
    Iterator<T> createIterator();
}

// Concrete Iterator
class NameIterator implements Iterator<String> {
    private List<String> names;
    private int index;

    public NameIterator(List<String> names) {
        this.names = names;
        this.index = 0;
    }

    @Override
    public boolean hasNext() {
        return index < names.size();
    }

    @Override
    public String next() {
        if (hasNext()) {
            return names.get(index++);
        }
        return null;
    }
}

// Concrete Aggregate
class NameRepository implements Container<String> {
    private List<String> names;

    public NameRepository() {
        this.names = new ArrayList<>();
    }

    public void addName(String name) {
        names.add(name);
    }

    @Override
    public Iterator<String> createIterator() {
        return new NameIterator(names);
    }
}

public class Main {
    public static void main(String[] args) {
        NameRepository nameRepository = new NameRepository();
        nameRepository.addName("Alice");
        nameRepository.addName("Bob");
        nameRepository.addName("Charlie");

        Iterator<String> iterator = nameRepository.createIterator();
        while (iterator.hasNext()) {
            System.out.println("Name: " + iterator.next());
        }
    }
}

Mediator Pattern

The Mediator Pattern defines an object that centralizes communication between objects in a system. It promotes loose coupling by ensuring that objects don't communicate directly with each other.

Example

import java.util.ArrayList;
import java.util.List;

// Mediator interface
interface Mediator {
    void sendMessage(String message, Colleague colleague);
}

// Colleague interface
abstract class Colleague {
    protected Mediator mediator;

    public Colleague(Mediator mediator) {
        this.mediator = mediator;
    }

    public abstract void receive(String message);

    public abstract void send(String message);
}

// Concrete Mediator
class ChatRoom implements Mediator {
    private List<Colleague> colleagues = new ArrayList<>();

    @Override
    public void sendMessage(String message, Colleague colleague) {
        for (Colleague c : colleagues) {
            if (c != colleague) {
                c.receive(message);
            }
        }
    }

    public void addColleague(Colleague colleague) {
        colleagues.add(colleague);
    }
}

// Concrete Colleague
class User extends Colleague {
    private String name;

    public User(String name, Mediator mediator) {
        super(mediator);
        this.name = name;
    }

    @Override
    public void receive(String message) {
        System.out.println(name + " received: " + message);
    }

    @Override
    public void send(String message) {
        System.out.println(name + " sent: " + message);
        mediator.sendMessage(message, this);
    }
}

public class Main {
    public static void main(String[] args) {
        ChatRoom chatRoom = new ChatRoom();

        User user1 = new User("Alice", chatRoom);
        User user2 = new User("Bob", chatRoom);
        User user3 = new User("Charlie", chatRoom);

        chatRoom.addColleague(user1);
        chatRoom.addColleague(user2);
        chatRoom.addColleague(user3);

        user1.send("Hello, everyone!");
    }
}

Memento Pattern

The Memento Pattern provides a way to capture and externalize an object's internal state so that it can be restored to that state later.

Example

import java.util.ArrayList;
import java.util.List;

// Memento class
class EditorMemento {
    private final String content;

    public EditorMemento(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }
}

// Originator class
class TextEditor {
    private String content;

    public void write(String content) {
        this.content = content;
    }

    public EditorMemento save() {
        return new EditorMemento(content);
    }

    public void restore(EditorMemento memento) {
        content = memento.getContent();
    }

    public String getContent() {
        return content;
    }
}

// Caretaker class
class History {
    private List<EditorMemento> mementos = new ArrayList<>();

    public void push(EditorMemento memento) {
        mementos.add(memento);
    }

    public EditorMemento pop() {
        if (!mementos.isEmpty()) {
            int lastIndex = mementos.size() - 1;
            EditorMemento lastMemento = mementos.get(lastIndex);
            mementos.remove(lastIndex);
            return lastMemento;
        }
        return null;
    }
}

public class Main {
    public static void main(String[] args) {
        TextEditor textEditor = new TextEditor();
        History history = new History();

        textEditor.write("Hello, World!");
        history.push(textEditor.save());

        textEditor.write("This is a new text.");
        history.push(textEditor.save());

        textEditor.write("Memento Pattern example.");
        System.out.println("Current Content: " + textEditor.getContent());

        // Restore to previous state
        textEditor.restore(history.pop());
        System.out.println("Restored Content: " + textEditor.getContent());

        // Restore to previous state
        textEditor.restore(history.pop());
        System.out.println("Restored Content: " + textEditor.getContent());
    }
}

Null Object Pattern

The Null Object Pattern provides an object as a surrogate for the lack of an object of a given type. It helps eliminate null references in your code.

Example

abstract class Animal {
    protected String name;

    public abstract String getName();
}

// Concrete class representing a real animal
class RealAnimal extends Animal {
    public RealAnimal(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

// Null object representing a "null" animal
class NullAnimal extends Animal {
    @Override
    public String getName() {
        return "No animal found";
    }
}

public class Main {
    public static void main(String[] args) {
        Animal realDog = new RealAnimal("Dog");
        Animal nullAnimal = new NullAnimal();

        System.out.println("Real Animal: " + realDog.getName());
        System.out.println("Null Animal: " + nullAnimal.getName());
    }
}

Observer Pattern

The Observer Pattern defines a one-to-many relationship between objects so that when one object changes state, all its dependents (observers) are notified and updated automatically. This pattern is widely used in event handling systems.

Example

import java.util.ArrayList;
import java.util.List;

// Subject (Observable)
class WeatherStation {
    private List<Observer> observers = new ArrayList<>();
    private int temperature;

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public void setTemperature(int temperature) {
        this.temperature = temperature;
        notifyObservers();
    }

    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temperature);
        }
    }
}

// Observer
interface Observer {
    void update(int temperature);
}

// Concrete Observer
class WeatherDisplay implements Observer {
    @Override
    public void update(int temperature) {
        System.out.println("Temperature is now " + temperature + " degrees Celsius.");
    }
}

public class Main {
    public static void main(String[] args) {
        WeatherStation weatherStation = new WeatherStation();
        WeatherDisplay display1 = new WeatherDisplay();
        WeatherDisplay display2 = new WeatherDisplay();

        weatherStation.addObserver(display1);
        weatherStation.addObserver(display2);

        weatherStation.setTemperature(25);
    }
}

State Pattern

The State Pattern allows an object to alter its behavior when its internal state changes. It involves defining a set of state objects and switching between them as needed.

Example

// State interface
interface State {
    void handleRequest(Context context);
}

// Concrete States
class StateIdle implements State {
    @Override
    public void handleRequest(Context context) {
        System.out.println("Context is in the idle state.");
        context.setState(new StateActive());
    }
}

class StateActive implements State {
    @Override
    public void handleRequest(Context context) {
        System.out.println("Context is in the active state.");
        context.setState(new StateIdle());
    }
}

// Context
class Context {
    private State currentState;

    public Context() {
        currentState = new StateIdle();
    }

    public void setState(State state) {
        currentState = state;
    }

    public void request() {
        currentState.handleRequest(this);
    }
}

public class Main {
    public static void main(String[] args) {
        Context context = new Context();

        context.request(); // Transition to active state
        context.request(); // Transition to idle state
    }
}

Strategy Pattern

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the client to choose the appropriate algorithm at runtime without altering the code that uses it.

Example

// Strategy interface
interface PaymentStrategy {
    void pay(int amount);
}

// Concrete Strategies
class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;

    public CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid $" + amount + " with credit card " + cardNumber);
    }
}

class PayPalPayment implements PaymentStrategy {
    private String email;

    public PayPalPayment(String email) {
        this.email = email;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid $" + amount + " with PayPal account " + email);
    }
}

// Context
class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int totalAmount) {
        paymentStrategy.pay(totalAmount);
    }
}

public class Main {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();

        cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9876-5432"));
        cart.checkout(100);

        cart.setPaymentStrategy(new PayPalPayment("example@example.com"));
        cart.checkout(50);
    }
}

Template Method Pattern

The Template Method Pattern defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.

Example

// Abstract class defining the template method
abstract class PaymentProcessor {
    public void processPayment() {
        authenticate();
        validatePaymentInfo();
        performPayment();
        sendConfirmationEmail();
    }

    abstract void authenticate();

    abstract void validatePaymentInfo();

    abstract void performPayment();

    void sendConfirmationEmail() {
        System.out.println("Sending payment confirmation email.");
    }
}

// Concrete subclass
class CreditCardPaymentProcessor extends PaymentProcessor {
    @Override
    void authenticate() {
        System.out.println("Authenticating credit card payment...");
    }

    @Override
    void validatePaymentInfo() {
        System.out.println("Validating credit card payment information...");
    }

    @Override
    void performPayment() {
        System.out.println("Processing credit card payment...");
    }
}

public class Main {
    public static void main(String[] args) {
        PaymentProcessor paymentProcessor = new CreditCardPaymentProcessor();
        paymentProcessor.processPayment();
    }
}

Visitor Pattern

The Visitor Pattern represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates.

Example

// Visitor interface
interface Visitor {
    void visit(Book book);
    void visit(Video video);
}

// Visitable interface
interface Visitable {
    void accept(Visitor visitor);
}

// Concrete Visitable classes
class Book implements Visitable {
    private String title;

    public Book(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class Video implements Visitable {
    private String title;

    public Video(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

// Concrete Visitor
class DiscountVisitor implements Visitor {
    @Override
    public void visit(Book book) {
        System.out.println("Applying a 10% discount to the book: " + book.getTitle());
    }

    @Override
    public void visit(Video video) {
        System.out.println("Applying a 15% discount to the video: " + video.getTitle());
    }
}

public class Main {
    public static void main(String[] args) {
        Visitable[] items = {new Book("Design Patterns"), new Video("Java Basics")};
        Visitor discountVisitor = new DiscountVisitor();

        for (Visitable item : items) {
            item.accept(discountVisitor);
        }
    }
}