Menu
Coddy logo textTech

팩토리 패턴

Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 87개 중 66번째.

Factory Pattern은 객체 생성을 별도의 메서드나 클래스에 위임하는 생성 디자인 패턴입니다. 코드에서 new를 직접 사용하는 대신, 팩토리에 객체를 생성해 달라고 요청합니다. 이는 공통 인터페이스나 부모를 공유하는 여러 관련 클래스가 있을 때 특히 유용합니다.

이메일, SMS 또는 푸시 notification을 보낼 수 있는 notification 시스템을 생각해 보세요. 팩터리가 없다면 코드는 모든 concrete class에 대해 알아야 합니다:

// Factory 없음 - 클라이언트가 모든 구체 클래스를 알아야 함
Notification notification;
if (type.equals("email")) {
    notification = new EmailNotification();
} else if (type.equals("sms")) {
    notification = new SMSNotification();
}

Factory Pattern을 사용하면 이 생성 로직을 중앙 집중화할 수 있습니다:

public interface Notification {
    void send(String message);
}

public class EmailNotification implements Notification {
    public void send(String message) {
        System.out.println("Email: " + message);
    }
}

public class SMSNotification implements Notification {
    public void send(String message) {
        System.out.println("SMS: " + message);
    }
}

public class NotificationFactory {
    public static Notification create(String type) {
        if (type.equals("email")) {
            return new EmailNotification();
        } else if (type.equals("sms")) {
            return new SMSNotification();
        }
        return null;
    }
}

이제 client 코드는 더 깔끔해졌고 concrete 클래스에 의존하지 않습니다:

Notification notification = NotificationFactory.create("email");
notification.send("Hello!");  // 출력: Email: Hello!

핵심 이점은 새로운 notification 유형을 추가할 때 팩토리만 업데이트하면 된다는 것입니다. client 코드는 변경되지 않습니다. 이는 interface를 대상으로 프로그래밍하는 원칙을 따르므로 시스템을 더 유연하고 확장하기 쉽게 만듭니다.

challenge icon

챌린지

쉬움

Factory Pattern을 사용하여 도형 그리기 시스템을 만들어 봅시다! 코드 전체에서 도형 객체를 직접 생성하는 대신, 간단한 문자열 식별자를 기반으로 다양한 도형 유형을 생성하는 factory에 생성 로직을 중앙 집중화합니다.

코드를 네 개의 파일로 구성합니다:

  • Shape.java: 모든 도형의 공통 계약 역할을 하는 Shape이라는 interface를 Define합니다. interface는 아무것도 반환하지 않고 그려지는 도형에 대한 정보를 출력하는 단일 draw() method를 declare해야 합니다.
  • Shapes.java: Shape interface를 implement하는 세 개의 class를 Create합니다:

    Circle - draw() method는 Drawing a Circle을 출력해야 합니다.

    Rectangle - draw() method는 Drawing a Rectangle을 출력해야 합니다.

    Triangle - draw() method는 Drawing a Triangle을 출력해야 합니다.

  • ShapeFactory.java: 도형 생성을 처리하는 factory class를 Create합니다. ShapeFactory에는 Shape을 return하는 static method createShape(String type)이 있어야 합니다. type 매개변수에 따라:
    • type이 "circle"과 equals하면 새로운 Circle을 return합니다.
    • type이 "rectangle"과 equals하면 새로운 Rectangle을 return합니다.
    • type이 "triangle"과 equals하면 새로운 Triangle을 return합니다.
    • 그 밖의 값에 대해서는 null을 return합니다.
  • Main.java: factory 시스템을 하나로 결합합니다! 두 개의 입력, 즉 두 도형 type(둘 다 Strings)을 받습니다.

    각 입력에 대해 ShapeFactory를 사용하여 도형을 Create하고 이를 Shape 변수에 저장합니다. factory가 유효한 도형(null이 아님)을 return하면 해당 도형의 draw() method를 call합니다. null을 return하면 Unknown shape: [type]을 출력합니다. 여기서 [type]은 제공된 입력입니다.

    두 입력을 순서대로 처리하며, 각각 자체 출력 줄에 표시합니다.

두 개의 입력을 순서대로 받습니다. 첫 번째 도형 type(String)과 두 번째 도형 type(String)입니다.

Main class가 new Circle()이나 new Rectangle()을 직접 사용하지 않는다는 점에 주목하세요. Main class는 Shape interface만 알고 factory에 객체를 Create해 달라고 요청합니다. 이것이 Factory Pattern의 강력한 점입니다. client 코드는 concrete class와 결합되지 않습니다!

직접 해보기

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 두 개의 도형 타입을 읽어옵니다
        String type1 = scanner.nextLine();
        String type2 = scanner.nextLine();
        
        // TODO: ShapeFactory를 사용하여 첫 번째 도형을 생성하세요
        // 도형이 null이 아니면 draw()를 호출하세요
        // If the shape is null, print "Unknown shape: [type]"
        
        // TODO: 두 번째 도형에 대해서도 동일하게 처리하세요
        
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러