PHpullh

JAVA · 객체지향

빌더 패턴

복잡한 객체 생성을 단계별로 수행하는 빌더 패턴을 구현합니다.

객체지향중급builder빌더패턴생성패턴불변

핵심 설명

복잡한 객체 생성을 단계별로 수행하는 빌더 패턴을 구현합니다.

Java code

public class HttpRequest {
    private final String method;
    private final String url;
    private final String body;
    private final Map<String, String> headers;
    private final int timeout;

    private HttpRequest(Builder builder) {
        this.method = builder.method;
        this.url = builder.url;
        this.body = builder.body;
        this.headers = Map.copyOf(builder.headers);
        this.timeout = builder.timeout;
    }

    // 정적 내부 빌더 클래스
    static class Builder {
        private final String method; // 필수
        private final String url;    // 필수
        private String body = "";
        private Map<String, String> headers = new java.util.HashMap<>();
        private int timeout = 30;

        Builder(String method, String url) {
            this.method = method;
            this.url = url;
        }

        Builder body(String body) { this.body = body; return this; }
        Builder header(String k, String v) { headers.put(k, v); return this; }
        Builder timeout(int sec) { this.timeout = sec; return this; }

        HttpRequest build() {
            return new HttpRequest(this);
        }
    }

    public static void main(String[] args) {
        HttpRequest req = new HttpRequest.Builder("POST", "/api/users")
            .header("Content-Type", "application/json")
            .body("{}")
            .timeout(10)
            .build();
    }
}

학습 팁

필수 파라미터는 빌더 생성자에, 선택 파라미터는 메서드 체인으로 설정하세요. Lombok @Builder로 자동 생성도 가능합니다.

주의할 점

빌더 인스턴스를 재사용하면 이전 설정이 남아있을 수 있습니다. build() 후에는 새 빌더를 만드세요.

자주 묻는 질문

빌더 패턴란 무엇인가요?

복잡한 객체 생성을 단계별로 수행하는 빌더 패턴을 구현합니다.

빌더 패턴 학습 시 주의할 점은 무엇인가요?

빌더 인스턴스를 재사용하면 이전 설정이 남아있을 수 있습니다. build() 후에는 새 빌더를 만드세요.