PHpullh
학습 라이브러리/Java/팩토리 메서드 패턴

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&lt;String, Supplier&gt; 로 등록 기반 팩토리를 만들면 OCP를 지킬 수 있습니다.

Continue Learning

Java 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.