JAVA · 객체지향
팩토리 메서드 패턴
객체 생성 로직을 팩토리 메서드로 캡슐화하여 유연성을 높입니다.
객체지향중급factory팩토리메서드생성패턴다형성
핵심 설명
객체 생성 로직을 팩토리 메서드로 캡슐화하여 유연성을 높입니다.
Java code
// 팩토리 메서드 — 인터페이스 기반
interface Notification {
void send(String message);
}
class EmailNotification implements Notification {
public void send(String msg) { System.out.println("이메일: " + msg); }
}
class SmsNotification implements Notification {
public void send(String msg) { System.out.println("SMS: " + msg); }
}
class PushNotification implements Notification {
public void send(String msg) { System.out.println("푸시: " + msg); }
}
// 팩토리 클래스
class NotificationFactory {
// 정적 팩토리 메서드
static Notification create(String type) {
return switch (type.toLowerCase()) {
case "email" -> new EmailNotification();
case "sms" -> new SmsNotification();
case "push" -> new PushNotification();
default -> throw new IllegalArgumentException(
"알 수 없는 타입: " + type);
};
}
// 간편 팩토리 메서드
static Notification email() { return new EmailNotification(); }
static Notification sms() { return new SmsNotification(); }
}
class Main {
public static void main(String[] args) {
Notification n = NotificationFactory.create("email");
n.send("안녕하세요!");
NotificationFactory.sms().send("인증코드: 1234");
}
}학습 팁
of(), from(), create() 등의 명명 규칙을 따르면 가독성이 좋습니다. List.of(), Optional.of()가 좋은 예입니다.
주의할 점
팩토리에 타입이 추가될 때마다 switch를 수정해야 합니다. Map<String, Supplier>로 등록 기반 팩토리를 만들면 OCP를 지킬 수 있습니다.
자주 묻는 질문
팩토리 메서드 패턴란 무엇인가요?
객체 생성 로직을 팩토리 메서드로 캡슐화하여 유연성을 높입니다.
팩토리 메서드 패턴 학습 시 주의할 점은 무엇인가요?
팩토리에 타입이 추가될 때마다 switch를 수정해야 합니다. Map<String, Supplier> 로 등록 기반 팩토리를 만들면 OCP를 지킬 수 있습니다.