프로그래밍/Java

빌더 (Builder) 클래스란?

Jinwookoh 2025. 3. 2. 19:33

빌더 클래스는 객체를 생성할 때 사용되는 디자인 패턴 중 하나인 빌더 패턴(Builder Pattern) 을 구현하는 클래스입니다. 객체 생성 시 복잡한 생성자 호출을 줄이고, 가독성을 높이며, 객체의 불변성을 유지하는 데 유용합니다.


1. 빌더 패턴을 사용하는 이유

(1) 생성자의 문제점

일반적으로 객체를 생성할 때 생성자를 사용하지만, 생성자의 매개변수가 많아지면 아래와 같은 문제점이 발생합니다.

public class User {
    private String name;
    private int age;
    private String email;
    private String address;

    public User(String name, int age, String email, String address) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.address = address;
    }
}

User user = new User("진욱", 30, "jinuk@example.com", "서울");

 

문제점

  • 생성자의 매개변수 개수가 많아질수록 관리가 어려움
  • 매개변수 순서를 잘못 입력하면 실수하기 쉬움
  • 선택적인 매개변수를 설정하려면 오버로딩을 여러 개 만들어야 함

(2) Setter를 사용한 방식의 문제점

Setter 메서드를 사용하면 일부 문제를 해결할 수 있지만, 객체가 변경 가능(Mutable)해진다는 단점이 있습니다.

User user = new User();
user.setName("진욱");
user.setAge(30);
user.setEmail("jinuk@example.com");
user.setAddress("서울");
 

문제점

  • 객체가 변경 가능(Mutable)하여 불변성을 보장하지 못함
  • 객체를 생성하는 과정이 분리되어 코드가 길어짐

2. 빌더 패턴 적용

빌더 패턴을 적용하면 가독성이 좋아지고, 불변성을 유지하며, 생성자 오버로딩 문제도 해결할 수 있습니다.

(1) 빌더 클래스 구현

public class User {
    private final String name;
    private final int age;
    private final String email;
    private final String address;

    private User(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.email = builder.email;
        this.address = builder.address;
    }

    public static class Builder {
        private String name;
        private int age;
        private String email;
        private String address;

        public Builder setName(String name) {
            this.name = name;
            return this;
        }

        public Builder setAge(int age) {
            this.age = age;
            return this;
        }

        public Builder setEmail(String email) {
            this.email = email;
            return this;
        }

        public Builder setAddress(String address) {
            this.address = address;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }
}

(2) 빌더 패턴 사용

User user = new User.Builder()
        .setName("진욱")
        .setAge(30)
        .setEmail("jinuk@example.com")
        .setAddress("서울")
        .build();
 

장점

  • 가독성이 좋아짐 → 각 필드에 대한 설정이 명확함
  • 불변성 유지 → final 필드를 사용하여 변경 불가능한 객체 생성
  • 필요한 필드만 설정 가능 → 선택적 매개변수 설정이 편리함

3. Lombok을 활용한 빌더 패턴

Lombok 라이브러리를 사용하면 빌더 클래스를 자동으로 생성할 수 있습니다.

(1) Lombok 적용 코드

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class User {
    private final String name;
    private final int age;
    private final String email;
    private final String address;
}

(2) 사용 방법

User user = User.builder()
        .name("진욱")
        .age(30)
        .email("jinuk@example.com")
        .address("서울")
        .build();
 

Lombok의 장점

  • 코드가 간결해짐 → 직접 빌더 클래스를 작성할 필요 없음
  • 자동으로 불변성 유지 → final 필드와 함께 사용 가능

4. 결론

빌더 패턴은 객체 생성 시 가독성을 높이고, 불변성을 유지하며, 선택적 매개변수 설정을 쉽게 할 수 있도록 도와주는 패턴입니다.
특히 Java에서는 Lombok의 @Builder를 활용하면 더 간결한 코드를 작성할 수 있습니다.

 

빌더 패턴이 필요한 경우

  • 매개변수가 많은 객체를 생성할 때
  • 불변성을 유지해야 할 때
  • 객체 생성 시 가독성을 높이고 싶을 때

'프로그래밍 > Java' 카테고리의 다른 글

IntStream.rangeClosed  (1) 2025.03.02
@Autowired 없어도 주입하는 방법  (0) 2025.03.02
자바 인터페이스의 세가지 유형 메소드  (0) 2025.03.02