1. Chain of Responsibility 패턴이란?
Chain of Responsibility(책임 연쇄) 패턴은
요청을 처리하는 여러 객체를 체인(연결) 형태로 묶어두고,각 객체가 요청을 처리할 수 있으면 처리하고,처리하지 못하면 다음 객체로 넘기는 패턴이다.
클라이언트는 “누가 처리하는지”를 알 필요 없이,
체인 맨 앞에만 요청을 던지면 된다.
2. 언제 사용하는 패턴인가?
다음과 같은 상황에서 유용하다.
- 요청 처리 규칙이 단계별로 나눠져 있을 때
- 예: 입력값 검증 → 권한 체크 → 비즈니스 규칙 체크 → 로깅 …
- 어떤 객체가 요청을 처리할지 정해두기 애매할 때
- 상황에 따라 다를 수 있거나, 나중에 추가될 수 있을 때
- if-else / switch가 너무 길어질 때
if(a) { … } else if(b) { … } else if(c) …같은 코드 제거
- 검증/필터/미들웨어 같은 ‘파이프라인’ 구조가 있을 때
- 예: 웹 서버에서 필터 체인, 미들웨어 체인 등
3. 구조
기본 구조는 다음과 같다.
- Handler (추상 핸들러)
- 공통 인터페이스 또는 추상 클래스
setNext()로 다음 핸들러를 연결handle()로 요청을 처리하고, 필요하면 다음 핸들러로 넘김
- ConcreteHandler (구체 핸들러들)
- 실제 처리 로직을 가지는 클래스들
- 조건에 맞으면 처리, 아니면
next.handle()호출
- Client
- 체인을 구성한 뒤, 맨 앞 핸들러에게만 요청을 전달
4. 소프트웨어 예시: 회원가입 입력값 검증 체인
4-1. 요구사항
회원가입 화면이 있고, 아래 순서대로 검증을 한다고 하자.
- 아이디가 비어 있지 않은지
- 이메일 형식이 올바른지
- 비밀번호 길이가 충분한지
- 비밀번호가 너무 단순하지 않은지
처음에는 이렇게 작성할 수 있다.
if (username == null || username.isBlank()) ...
if (!email.contains("@")) ...
if (password.length() < 8) ...
if (password.equals("1234")) ...
요구사항이 늘어날수록 if-else가 계속 늘어나고,
검증 순서를 바꾸거나 일부만 재사용하기도 어려워진다.
➡ 이를 책임 연쇄 패턴으로 분리해보자.
4-2. 요청 데이터 객체
public class RegistrationRequest {
private final String username;
private final String email;
private final String password;
public RegistrationRequest(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getPassword() { return password; }
}
4-3. 추상 핸들러
public abstract class Handler {
private Handler next;
// 다음 핸들러를 연결
public Handler setNext(Handler next) {
this.next = next;
return next; // 체이닝 가능하게 반환
}
// 템플릿 메서드: 공통 흐름
public void handle(RegistrationRequest request) {
// 현재 핸들러의 검증
check(request);
// 다음 핸들러가 있으면 넘김
if (next != null) {
next.handle(request);
}
}
// 각 핸들러에서 실제 검증 로직 구현
protected abstract void check(RegistrationRequest request);
}
핵심은:
- 체인 연결은
setNext()
- 요청 처리 흐름은
handle()
- 실제 검증 로직은
check()에서 구현
4-4. 구체 핸들러들
1) 아이디 공백 체크
public class UsernameNotEmptyHandler extends Handler {
@Override
protected void check(RegistrationRequest request) {
String username = request.getUsername();
if (username == null || username.isBlank()) {
throw new IllegalArgumentException("아이디를 입력해야 한다.");
}
System.out.println("UsernameNotEmptyHandler: OK");
}
}
2) 이메일 형식 체크(간단 버전)
public class EmailFormatHandler extends Handler {
@Override
protected void check(RegistrationRequest request) {
String email = request.getEmail();
if (email == null || !email.contains("@")) {
throw new IllegalArgumentException("이메일 형식이 올바르지 않다.");
}
System.out.println("EmailFormatHandler: OK");
}
}
3) 비밀번호 길이 체크
public class PasswordLengthHandler extends Handler {
private final int minLength;
public PasswordLengthHandler(int minLength) {
this.minLength = minLength;
}
@Override
protected void check(RegistrationRequest request) {
String password = request.getPassword();
if (password == null || password.length() < minLength) {
throw new IllegalArgumentException(
"비밀번호는 최소 " + minLength + "자리 이상이어야 한다."
);
}
System.out.println("PasswordLengthHandler: OK");
}
}
4) 비밀번호 단순 패턴 체크
public class PasswordSimplePatternHandler extends Handler {
@Override
protected void check(RegistrationRequest request) {
String password = request.getPassword();
if ("1234".equals(password) || "password".equalsIgnoreCase(password)) {
throw new IllegalArgumentException("너무 단순한 비밀번호는 사용할 수 없다.");
}
System.out.println("PasswordSimplePatternHandler: OK");
}
}
4-5. 체인 구성 및 사용
public class RegistrationService {
private final Handler handlerChain;
public RegistrationService() {
// 체인 구성
Handler username = new UsernameNotEmptyHandler();
Handler email = new EmailFormatHandler();
Handler pwLen = new PasswordLengthHandler(8);
Handler pwSimple = new PasswordSimplePatternHandler();
// username → email → pwLen → pwSimple 순서로 연결
username.setNext(email)
.setNext(pwLen)
.setNext(pwSimple);
this.handlerChain = username;
}
public void register(String username, String email, String password) {
RegistrationRequest request = new RegistrationRequest(username, email, password);
// 체인 맨 앞에만 요청
handlerChain.handle(request);
// 여기까지 예외 없이 통과했다면 실제 회원가입 진행
System.out.println("모든 검증 통과. 회원가입 처리 진행.");
}
}
사용 예:
public class Main {
public static void main(String[] args) {
RegistrationService service = new RegistrationService();
service.register("hong", "hong@test.com", "securePass1");
}
}
5. 장단점
✅ 장점
- if-else 체인 제거
- 검증/처리 로직을 클래스 단위로 분리할 수 있다.
- 확장성이 좋다
- 새로운 검증 규칙이 필요하면 Handler를 하나 더 만들고 체인에 연결만 하면 된다.
- 순서 변경이 쉽다
- 체인을 재구성하면 실행 순서를 쉽게 바꿀 수 있다.
- 단일 책임 원칙(SRP)에 잘 맞는다
- 각 핸들러는 하나의 책임에만 집중한다.
❌ 단점
- 디버깅이 다소 불편할 수 있다
- 어느 핸들러에서 예외가 발생했는지 추적해야 한다.
- 체인 구조가 복잡해질 수 있다
- 핸들러 개수가 많아지면 흐름을 이해하기 어려워질 수 있다.
- 순서가 중요해지는 경우가 많다
- 잘못된 순서로 체인을 구성하면 로직이 비정상적으로 동작할 수 있다.
6. 한 줄 정리
Chain of Responsibility 패턴은입력 검증, 필터, 미들웨어처럼 단계적으로 처리해야 하는 로직을 여러 핸들러 객체의 체인으로 분리해 if-else 지옥을 없애는 패턴이다.
Share article