📘 빌더 패턴이란?
빌더 패턴은 복잡한 객체의 생성 과정을 분리해서
동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있도록 하는 생성 패턴이다.
주로 필드가 많거나 생성자가 복잡한 객체의 생성 시 가독성과 유지보수를 높이기 위해 사용되었다.
🔧 특징
- 객체 생성 과정을 단계별로 분리해서 처리할 수 있다.
- 가독성이 뛰어난 코드를 작성할 수 있다.
- 생성자의 매개변수가 많을 때 발생하는 혼란을 줄일 수 있다.
- 불변 객체 생성에 적합하다.
🧱 구조
- Product: 최종적으로 생성되는 객체이다.
- Builder: Product를 생성하기 위한 인터페이스 또는 추상 클래스이다.
- ConcreteBuilder: Builder를 구현해서 실제 객체 생성을 수행한다.
- Director: Builder를 이용해 객체를 생성하는 역할을 한다.
🧑💻 예제 코드 (Java)
public class Computer {
private String cpu;
private String ram;
private String storage;
public static class Builder {
private String cpu;
private String ram;
private String storage;
public Builder cpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder ram(String ram) {
this.ram = ram;
return this;
}
public Builder storage(String storage) {
this.storage = storage;
return this;
}
public Computer build() {
return new Computer(this);
}
}
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.storage = builder.storage;
}
}
✅ 사용 방법
Computer computer = new Computer.Builder()
.cpu("Intel i7")
.ram("16GB")
.storage("1TB SSD")
.build();
위와 같이 메서드 체인을 통해 직관적으로 객체를 생성할 수 있었다.
👍 장점
- 필드가 많아도 생성자보다 유연하고 읽기 쉬운 코드 작성이 가능하다.
- 선택적인 매개변수 설정이 가능하다.
- 불변성 유지가 쉬운 객체 생성이 가능하다.
🙎 단점
- 클래스 수가 증가해 코드가 길어진다.
- 비교적 단순한 객체에 사용하면 과도한 설계가 될 수 있다.
📝 언제 사용하면 좋을까?
- 생성자에 넘겨야 할 매개변수가 많을 때
- 생성자 오버로딩이 너무 많아지는 경우
- 객체의 일부 필드만 선택적으로 설정하고 싶을 때
- **불변 객체(immutable object)**를 만들고 싶을 때
'컴퓨터 과학(CS) > 디자인패턴' 카테고리의 다른 글
[생성 패턴] 싱글톤(Singleton) (0) | 2025.04.02 |
---|---|
디자인 패턴이란? (0) | 2025.04.02 |