M5 · Communication Between ObjectsSession 10-11BehavioralReshaped in KotlinOutline

Intent. Pass a request along a chain until some handler takes it, and can stop it.

In Kotlin. A list of interceptors walked in order – the shape OkHttp and Ktor both use.

Structurally a chain, like Decorator, with one decisive difference: a handler may stop the request instead of passing it on. That single capability is what makes it right for auth, rate limiting, and routing. OkHttp’s interceptor stack is this pattern in production, which makes it easy to study from real code.

Structure

classDiagram
    class Handler {
        <<interface>>
        +setNext(h) Handler
        +handle(req)
    }
    class AuthHandler {
        +handle(req)
    }
    class RateLimitHandler {
        +handle(req)
    }
    class RouteHandler {
        +handle(req)
    }
    Handler <|.. AuthHandler
    Handler <|.. RateLimitHandler
    Handler <|.. RouteHandler
    Handler o--> Handler : next, may stop here

Telling It Apart

Patterns whose structure looks the same but whose intent does not. See the Confusing Pairs reference.

  • Decorator — Keep the interface and add responsibilities, stackable at runtime.