Factory Method Pattern (팩토리 메서드 패턴)
Java를 공부하다 보면 객체를 생성할 때 항상 new 를 사용한다고 생각하기 쉽다.
Animal animal = new Dog();
하지만 객체 생성 로직이 복잡해지고 종류가 많아지면 코드 곳곳에 new 가 흩어지게 된다.
if (type.equals("DOG")) {
return new Dog();
}
if (type.equals("CAT")) {
return new Cat();
}
if (type.equals("TIGER")) {
return new Tiger();
}
새로운 동물이 추가될 때마다 코드를 수정해야 한다.
이 문제를 해결하기 위해 등장한 패턴이 Factory Method Pattern 이다.
1. Factory Method Pattern 이란?
객체 생성 책임을 별도의 Factory에 위임하는 패턴이다.
객체를 사용하는 쪽은
new Dog()
를 직접 호출하지 않는다.
대신 Factory에게 요청한다.
Animal animal = factory.createAnimal();
객체 생성 방법은 Factory가 결정한다.
2. 왜 사용하는가?
일반적인 방식
public class AnimalService {
public Animal create(String type) {
if ("DOG".equals(type)) {
return new Dog();
}
if ("CAT".equals(type)) {
return new Cat();
}
throw new IllegalArgumentException();
}
}
문제점
- 객체 생성 코드가 여기저기 흩어짐
- 새로운 타입 추가 시 수정 발생
- OCP 위반
- 생성 책임과 사용 책임이 섞임
3. 구조
Factory Method Pattern의 핵심은
Client
↓
Creator
↓
Product
이다.
Product
생성될 객체의 공통 인터페이스
public interface Animal {
void sound();
}
Concrete Product
실제 구현체
public class Dog implements Animal {
@Override
public void sound() {
System.out.println("멍멍");
}
}
public class Cat implements Animal {
@Override
public void sound() {
System.out.println("야옹");
}
}
Creator
Factory 역할
public abstract class AnimalFactory {
public abstract Animal createAnimal();
}
Concrete Creator
실제 생성 담당
public class DogFactory extends AnimalFactory {
@Override
public Animal createAnimal() {
return new Dog();
}
}
public class CatFactory extends AnimalFactory {
@Override
public Animal createAnimal() {
return new Cat();
}
}
Client
AnimalFactory factory = new DogFactory();
Animal animal = factory.createAnimal();
animal.sound();
출력
멍멍
4. 동작 흐름
Client
↓
DogFactory.createAnimal()
↓
Dog 생성
↓
Animal 반환
Client는
new Dog()
를 모른다.
단지
Animal
만 알면 된다.
5. Factory Method Pattern의 핵심
핵심은
"객체 생성 책임을 하위 클래스에게 위임한다"
이다.
예를 들어
public abstract class NotificationFactory {
public abstract Notification create();
}
이메일
public class EmailFactory
extends NotificationFactory {
@Override
public Notification create() {
return new EmailNotification();
}
}
카카오톡
public class KakaoFactory
extends NotificationFactory {
@Override
public Notification create() {
return new KakaoNotification();
}
}
사용자는
Notification notification =
factory.create();
만 호출한다.
6. OCP를 만족하는 이유
새로운 기능 추가 시
public class SmsNotification
implements Notification {
}
public class SmsFactory
extends NotificationFactory {
@Override
public Notification create() {
return new SmsNotification();
}
}
추가만 하면 된다.
기존 코드는 수정하지 않는다.
7. 실무에서는 이렇게 구현하는 경우가 더 많다
GoF 책의 전통적인 방식보다
실무에서는 Factory 클래스를 하나 두는 경우가 많다.
public class AnimalFactory {
public Animal create(String type) {
switch (type) {
case "DOG":
return new Dog();
case "CAT":
return new Cat();
default:
throw new IllegalArgumentException();
}
}
}
사용
Animal animal =
factory.create("DOG");
엄밀히 말하면
이것은 Simple Factory에 가깝다.
하지만 실무에서는 Factory Method라고 부르는 경우도 많다.
8. Spring에서 만나는 Factory
실제로 Spring 내부에도 Factory 개념이 많다.
예)
BeanFactory
Spring Framework 의 가장 핵심적인 Factory 인터페이스다.
FactoryBean
특수한 객체 생성용 Factory
SqlSessionFactory
MyBatis 에서 사용하는 Factory
EntityManagerFactory
Jakarta Persistence 의 Factory
9. Factory Method vs Static Factory Method
많이 헷갈리는 부분이다.
Static Factory Method
User.create();
LocalDate.now();
Optional.of();
특정 객체를 생성하는 static 메서드
Factory Method Pattern
AnimalFactory
DogFactory
CatFactory
객체 생성 구조 자체를 추상화하는 디자인 패턴
Factory Method Pattern 장점
생성 로직 분리
new Dog()
를 숨길 수 있다.
OCP 만족
새 구현체 추가가 쉽다.
다형성 활용
Animal animal =
factory.createAnimal();
사용자는 구현체를 몰라도 된다.
결합도 감소
Dog
Cat
Tiger
에 직접 의존하지 않는다.
Factory Method Pattern 단점
클래스 수 증가
Animal
Dog
Cat
AnimalFactory
DogFactory
CatFactory
객체 수가 많아질수록 클래스가 급격히 증가한다.
단순한 프로젝트에는 과할 수 있음
new Dog()
한 줄이면 끝나는 것을
Factory까지 만들 필요가 없는 경우도 많다.
Builder Pattern과 차이
Builder는
User.builder()
.name("kim")
.age(30)
.build();
복잡한 객체 생성이 목적이다.
Factory Method는
factory.createAnimal();
어떤 객체를 생성할지 결정하는 것이 목적이다.
Strategy Pattern과 차이
Factory Method
어떤 객체를 만들까?
Strategy Pattern
만들어진 객체가 어떤 동작을 할까?
면접 한 줄 정리
Factory Method Pattern은 객체 생성 책임을 별도의 Factory 계층에 위임하여 객체 생성과 사용을 분리하는 생성 패턴이다. 이를 통해 다형성을 활용하고 결합도를 낮추며 OCP(Open-Closed Principle)를 만족시킬 수 있다.
실무에서는 BeanFactory, FactoryBean, SqlSessionFactory, EntityManagerFactory 등 다양한 형태로 활용되며, 정적 팩토리 메서드(Static Factory Method)와는 다른 개념이다.
'language > java' 카테고리의 다른 글
| 번외편 - Java Comparator vs JavaScript sort() (0) | 2026.06.04 |
|---|---|
| Static Factory Method (정적 팩토리 메서드) (0) | 2026.06.01 |
| Virtual Thread (Java 21) 완벽 이해하기 (0) | 2026.06.01 |
| 병렬 Stream(parallelStream) 주의점 완벽 이해하기 (0) | 2026.06.01 |
| ConcurrentHashMap 동시성 처리 완벽 이해하기 (0) | 2026.06.01 |
댓글