PHpullh
학습 라이브러리/Kotlin/체인 오브 책임 (Chain of Responsibility)

KOTLIN · 디자인패턴

체인 오브 책임 (Chain of Responsibility)

요청을 처리할 수 있는 핸들러 체인을 구성합니다. 미들웨어, 필터, 검증 파이프라인에 활용됩니다.

디자인패턴중급chain-of-responsibilitymiddlewarepipelinefilter

핵심 설명

요청을 처리할 수 있는 핸들러 체인을 구성합니다. 미들웨어, 필터, 검증 파이프라인에 활용됩니다.

Kotlin code

data class Request(val path: String, val headers: Map<String, String>, val body: String)
data class Response(val code: Int, val body: String)

fun interface Middleware {
    fun handle(request: Request, next: (Request) -> Response): Response
}

val authMiddleware = Middleware { req, next ->
    if (req.headers.containsKey("Authorization")) {
        println("[Auth] 인증 통과")
        next(req)
    } else {
        Response(401, "인증 필요")
    }
}

val loggingMiddleware = Middleware { req, next ->
    println("[Log] ${req.path} 요청")
    val response = next(req)
    println("[Log] 응답: ${response.code}")
    response
}

val rateLimitMiddleware = Middleware { req, next ->
    println("[RateLimit] 요청 허용")
    next(req)
}

fun buildChain(middlewares: List<Middleware>, handler: (Request) -> Response): (Request) -> Response =
    middlewares.foldRight(handler) { mw, next -> { req -> mw.handle(req, next) } }

fun main() {
    val chain = buildChain(
        listOf(loggingMiddleware, authMiddleware, rateLimitMiddleware)
    ) { req -> Response(200, "응답: ${req.path}") }

    val req = Request("/api/data", mapOf("Authorization" to "Bearer xyz"), "")
    val resp = chain(req)
    println("최종: ${resp.code} - ${resp.body}")
}

학습 팁

foldRight로 미들웨어 체인을 구성하면 등록 순서대로 실행됩니다. 순서를 바꾸기만 해도 동작이 달라집니다.

주의할 점

체인에서 next(req)를 호출하지 않으면 후속 핸들러가 실행되지 않습니다. 의도적인 차단이 아니라면 반드시 next를 호출하세요.

자주 묻는 질문

체인 오브 책임 (Chain of Responsibility)란 무엇인가요?

요청을 처리할 수 있는 핸들러 체인을 구성합니다. 미들웨어, 필터, 검증 파이프라인에 활용됩니다.

체인 오브 책임 (Chain of Responsibility) 학습 시 주의할 점은 무엇인가요?

체인에서 next(req) 를 호출하지 않으면 후속 핸들러가 실행되지 않습니다. 의도적인 차단이 아니라면 반드시 next 를 호출하세요.