| 항목 | Builder 패턴 | Factory 패턴 |
|---|---|---|
| 목적 | 복잡한 객체를 단계적으로 생성 | 객체 생성 캡슐화 및 다형성 처리 |
| 주요 특징 | 필드별로 유연하게 설정 가능 | 서브 클래스 결정, 생성 로직 감춤 |
| 사용 예 | DTO, Entity, 복잡한 설정 객체 | 전략 패턴, DB 커넥션, 전략별 서비스 |
| Spring에서 | @Builder, Lombok | @Bean, Factory 클래스, ApplicationContext.getBean() 등 |
@Builder
public class User {
private String name;
private int age;
private String email;
}
User user = User.builder()
.name("kim")
.email("kim@example.com")
.age(25)
.build();
장점:
final과 조합)단점:
@Builder.Default 같은 설정 안 하면 초기화 누락될 수도 있음인터페이스 + 구현체 + 팩토리
public interface PaymentService {
void pay(int amount);
}
public class KakaoPayService implements PaymentService {
public void pay(int amount) {
System.out.println("KakaoPay로 결제: " + amount);
}
}
public class PaycoService implements PaymentService {
public void pay(int amount) {
System.out.println("Payco로 결제: " + amount);
}
}
public class PaymentFactory {
public static PaymentService getService(String type) {
switch (type) {
case "kakao": return new KakaoPayService();
case "payco": return new PaycoService();
default: throw new IllegalArgumentException("지원 안 함");
}
}
}
PaymentService service = PaymentFactory.getService("kakao");
service.pay(5000);
장점:
단점:
| 상황 | 추천 패턴 |
|---|---|
| 필드가 많고 생성자 인자가 복잡한 경우 | ✅ Builder |
| 구현체가 여러 개 있고 런타임에 결정되는 경우 | ✅ Factory |
| 외부 라이브러리 객체 설정이 복잡할 때 | Builder or Factory 모두 가능 |
| Spring에서 Bean 생성 조건 다를 때 | Factory + DI 조합 (@Bean, @Conditional) |