Chain of Responsibility

Pass request along chain of handlers

Overview

Chain of Responsibility passes requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.

Code Example

java
1public abstract class Logger {
2    public static int INFO = 1;
3    public static int DEBUG = 2;
4    public static int ERROR = 3;
5    
6    protected int level;
7    protected Logger nextLogger;
8    
9    public void setNext(Logger nextLogger) { this.nextLogger = nextLogger; }
10    
11    public void logMessage(int level, String message) {
12        if (this.level <= level) { write(message); }
13        if (nextLogger != null) { nextLogger.logMessage(level, message); }
14    }
15    
16    protected abstract void write(String message);
17}
18
19// Implementations: ConsoleLogger(INFO), FileLogger(DEBUG), ErrorLogger(ERROR)...

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In
Chain of Responsibility - Behavioral Patterns | LLD | Revise Algo