Menu
Coddy logo textTech

팩토리 패턴

Coddy C# 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 70개 중 53번째.

Factory 패턴은 객체 생성을 별도의 메서드나 클래스에 위임하는 생성 패턴입니다. 코드에서 new를 직접 사용하는 대신, factory에 객체를 생성해 달라고 요청합니다. 이렇게 하면 creation logic이 중앙화되고 코드가 더 유연해집니다.

서로 다른 유형의 문서를 생성해야 하는 상황을 생각해 보세요. factory가 없다면 코드가 특정 클래스에 강하게 결합됩니다:

// Factory 없이 - 흩어진 생성 로직
IDocument doc;
if (type == "pdf")
    doc = new PdfDocument();
else if (type == "word")
    doc = new WordDocument();

factory는 이러한 의사 결정을 한곳에 캡슐화합니다:

public interface IDocument
{
    void Open();
}

public class PdfDocument : IDocument
{
    public void Open() => Console.WriteLine("Opening PDF");
}

public class WordDocument : IDocument
{
    public void Open() => Console.WriteLine("Opening Word");
}

public class DocumentFactory
{
    public IDocument Create(string type)
    {
        return type switch
        {
            "pdf" => new PdfDocument(),
            "word" => new WordDocument(),
            _ => throw new ArgumentException("Unknown type")
        };
    }
}

이제 클라이언트 코드는 구체적인 클래스를 알지 못한 채 필요한 것을 간단히 요청합니다:

var factory = new DocumentFactory();
IDocument doc = factory.Create("pdf");
doc.Open();  // PDF 열기

Factory 패턴은 나중에 새로운 유형을 추가해야 할 때 빛을 발합니다. SpreadsheetDocument를 추가하려면 문서가 생성되는 모든 곳이 아니라 factory에서만 변경하면 됩니다. 이러한 분리는 코드베이스를 더 쉽게 유지 관리하고 테스트할 수 있게 합니다.

challenge icon

챌린지

쉬움

Factory 패턴을 사용하여 notification system을 만들어 봅시다. 코드 전체에서 서로 다른 notification type을 직접 생성하는 대신, 간단한 string identifier를 기반으로 어떤 notification을 생성할지 결정하는 factory class에 creation logic을 중앙화합니다.

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

  • Notification.cs: Notifications namespace에 INotification interface를 Define하고, string을 returns하는 단일 method Send(string message)를 추가합니다. 그런 다음 이 interface를 Implement하는 세 개의 class를 Create합니다:
    • EmailNotification - "Email: {message}"을 returns
    • SmsNotification - "SMS: {message}"을 returns
    • PushNotification - "Push: {message}"을 returns
  • NotificationFactory.cs: 같은 namespace에 NotificationFactory class를 Create하고, type string을 based on 적절한 INotification을 returns하는 Create(string type) method를 추가합니다:
    • "email"EmailNotification을 returns
    • "sms"SmsNotification을 returns
    • "push"PushNotification을 returns
    인식할 수 없는 type인 경우 default로 EmailNotification을 return합니다.
  • Program.cs: factory instance를 Create하고 이를 사용하여 input에 based notification을 생성함으로써 모든 내용을 하나로 결합합니다. factory가 어떤 구체적인 class를 instance화할지에 대한 모든 의사 결정을 처리합니다.

두 개의 input을 받습니다:

  • notification type (예: sms)
  • 보낼 message (예: Your order has shipped)

factory를 사용하여 적절한 notification type을 Create한 다음, message와 함께 해당 notification의 Send method를 Call하고 result를 print합니다.

예를 들어 input이 pushMeeting in 5 minutes인 경우 output은 다음과 같아야 합니다:

Push: Meeting in 5 minutes

main code에서는 new EmailNotification() 또는 이와 유사한 것을 전혀 사용하지 않는다는 점에 주목하세요. 단순히 factory에 필요한 것을 요청할 뿐입니다. 나중에 SlackNotification을 추가하더라도 notification을 생성하는 모든 위치가 아니라 factory만 update하면 됩니다!

직접 해보기

using System;
using Notifications;

class Program
{
    public static void Main(string[] args)
    {
        // 입력 읽기
        string type = Console.ReadLine();
        string message = Console.ReadLine();

        // TODO: NotificationFactory 인스턴스 생성

        // TODO: 팩토리를 사용하여 적절한 알림 생성

        // TODO: Send 메서드를 호출하고 결과 출력
    }
}
quiz icon실력 점검

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

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

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