🤖

본 콘텐츠의 이미지 및 내용은 AI로 생성되었습니다.

⚠️

본 콘텐츠의 이미지 및 내용을 무단으로 복제, 배포, 수정하여 사용할 경우 저작권법에 의해 법적 제재를 받을 수 있습니다.

이미지 로딩 중...

Factory Pattern 디자인 패턴 완벽 가이드 - 슬라이드 1/13
A

AI Generated

2025. 11. 3. · 13 Views

Factory Pattern 디자인 패턴 완벽 가이드

객체 생성 로직을 캡슐화하여 유연한 코드를 작성하는 Factory Pattern을 학습합니다. 실무에서 자주 사용되는 Simple Factory, Factory Method, Abstract Factory 패턴을 코드 예제와 함께 설명합니다.


카테고리:TypeScript
언어:TypeScript
메인 태그:#TypeScript
서브 태그:
#FactoryPattern#DesignPattern#ObjectCreation#SoftwareArchitecture

들어가며

이 글에서는 Factory Pattern 디자인 패턴 완벽 가이드에 대해 상세히 알아보겠습니다. 총 12가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.

목차

  1. Simple_Factory_기본
  2. Factory_Method_패턴
  3. Abstract_Factory_패턴
  4. Factory_with_Dependency_Injection
  5. Factory_with_Registry
  6. Parameterized_Factory
  7. Factory_with_Singleton
  8. Async_Factory_Pattern
  9. Generic_Factory_Pattern
  10. Builder_Pattern_vs_Factory
  11. Factory_with_Validation
  12. Real_World_API_Client_Factory

1. Simple Factory 기본

개요

가장 기본적인 Factory 패턴으로, 객체 생성 로직을 하나의 클래스에 집중시킵니다. 클라이언트 코드에서 new 키워드 사용을 줄여줍니다.

코드 예제

class CarFactory {
  static createCar(type: string) {
    if (type === 'sedan') return { type: 'Sedan', wheels: 4 };
    if (type === 'suv') return { type: 'SUV', wheels: 4 };
    throw new Error('Unknown car type');
  }
}

const myCar = CarFactory.createCar('sedan');
console.log(myCar); // { type: 'Sedan', wheels: 4 }

설명

static 메서드를 사용해 type에 따라 다른 객체를 생성합니다. 객체 생성 로직이 한 곳에 모여 관리가 쉬워집니다.


2. Factory Method 패턴

개요

추상 클래스에서 객체 생성 메서드를 정의하고, 서브클래스에서 실제 생성 로직을 구현합니다. 확장에 열려있고 수정에 닫혀있는 구조입니다.

코드 예제

abstract class NotificationFactory {
  abstract createNotification(): { send: () => void };

  notify() {
    const notification = this.createNotification();
    notification.send();
  }
}

class EmailFactory extends NotificationFactory {
  createNotification() {
    return { send: () => console.log('Email sent!') };
  }
}

new EmailFactory().notify(); // Email sent!

설명

부모 클래스는 인터페이스만 정의하고, 자식 클래스가 구체적인 객체 생성을 담당합니다. 새로운 타입 추가 시 기존 코드 수정이 불필요합니다.


3. Abstract Factory 패턴

개요

관련된 객체들의 패밀리를 생성하는 인터페이스를 제공합니다. 여러 제품군을 일관되게 생성할 때 유용합니다.

코드 예제

interface UIFactory {
  createButton(): { render: () => string };
  createInput(): { render: () => string };
}

class DarkThemeFactory implements UIFactory {
  createButton() {
    return { render: () => 'Dark Button' };
  }
  createInput() {
    return { render: () => 'Dark Input' };
  }
}

const factory = new DarkThemeFactory();
console.log(factory.createButton().render());

설명

하나의 팩토리가 여러 관련 제품을 생성합니다. 테마 전환 같은 경우 팩토리만 교체하면 전체 UI가 일관되게 변경됩니다.


4. Factory with Dependency Injection

개요

Factory 패턴과 의존성 주입을 결합하여 더 유연한 구조를 만듭니다. 테스트하기 쉽고 결합도가 낮은 코드가 됩니다.

코드 예제

class Logger {
  log(msg: string) { console.log(msg); }
}

class UserFactory {
  constructor(private logger: Logger) {}

  createUser(name: string) {
    this.logger.log(`Creating user: ${name}`);
    return { name, createdAt: new Date() };
  }
}

const factory = new UserFactory(new Logger());
factory.createUser('Alice');

설명

Logger를 생성자로 주입받아 Factory가 외부 의존성을 직접 생성하지 않습니다. 테스트 시 Mock Logger를 주입할 수 있습니다.


5. Factory with Registry

개요

팩토리에 타입을 등록하고 동적으로 객체를 생성하는 패턴입니다. 런타임에 새로운 타입을 추가할 수 있어 확장성이 뛰어납니다.

코드 예제

class ShapeFactory {
  private creators = new Map<string, () => any>();

  register(type: string, creator: () => any) {
    this.creators.set(type, creator);
  }

  create(type: string) {
    const creator = this.creators.get(type);
    return creator ? creator() : null;
  }
}

const factory = new ShapeFactory();
factory.register('circle', () => ({ shape: 'circle', radius: 5 }));
console.log(factory.create('circle'));

설명

Map을 사용해 타입과 생성 함수를 매핑합니다. if-else 체인 없이 깔끔하게 객체를 생성하고, 런타임에 타입을 추가할 수 있습니다.


6. Parameterized Factory

개요

Factory 메서드에 여러 매개변수를 전달하여 다양한 조합의 객체를 생성합니다. 복잡한 객체 생성을 단순화합니다.

코드 예제

class DatabaseFactory {
  static create(type: string, config: { host: string; port: number }) {
    return {
      type,
      connection: `${config.host}:${config.port}`,
      connect: () => console.log(`Connected to ${type}`)
    };
  }
}

const db = DatabaseFactory.create('PostgreSQL', {
  host: 'localhost',
  port: 5432
});
db.connect(); // Connected to PostgreSQL

설명

타입뿐만 아니라 설정 객체도 받아 더 유연한 객체 생성이 가능합니다. 복잡한 설정을 캡슐화하여 사용자 친화적인 API를 제공합니다.


7. Factory with Singleton

개요

Factory 패턴과 Singleton 패턴을 결합하여 인스턴스를 재사용합니다. 메모리 효율적이고 상태를 공유해야 할 때 유용합니다.

코드 예제

class ConfigFactory {
  private static instances = new Map<string, any>();

  static getConfig(env: string) {
    if (!this.instances.has(env)) {
      this.instances.set(env, {
        env,
        settings: { debug: env === 'dev' }
      });
    }
    return this.instances.get(env);
  }
}

const config1 = ConfigFactory.getConfig('dev');
const config2 = ConfigFactory.getConfig('dev');
console.log(config1 === config2); // true

설명

Map을 사용해 생성된 인스턴스를 캐싱합니다. 같은 타입을 요청하면 새로 생성하지 않고 기존 인스턴스를 반환하여 리소스를 절약합니다.


8. Async Factory Pattern

개요

비동기 작업이 필요한 객체를 생성할 때 사용하는 Factory 패턴입니다. API 호출이나 파일 로딩 등의 작업에 적합합니다.

코드 예제

class UserFactory {
  static async create(userId: string) {
    // API 호출 시뮬레이션
    const userData = await new Promise(resolve =>
      setTimeout(() => resolve({ id: userId, name: 'User' }), 100)
    );
    return {
      ...userData as object,
      greet() { console.log('Hello!') }
    };
  }
}

const user = await UserFactory.create('123');
user.greet(); // Hello!

설명

async/await를 사용해 비동기 초기화가 필요한 객체를 생성합니다. Promise를 반환하여 외부 리소스 로딩이 완료된 후 객체를 사용할 수 있습니다.


9. Generic Factory Pattern

개요

TypeScript의 제네릭을 활용하여 타입 안전한 Factory를 만듭니다. 컴파일 타임에 타입 오류를 잡을 수 있습니다.

코드 예제

interface Product {
  name: string;
  create(): void;
}

class Factory<T extends Product> {
  constructor(private ctor: new () => T) {}

  createProduct(): T {
    return new this.ctor();
  }
}

class Book implements Product {
  name = 'Book';
  create() { console.log('Book created'); }
}

const factory = new Factory(Book);
const book = factory.createProduct(); // Type: Book

설명

제네릭과 생성자 타입을 사용해 어떤 Product 타입도 생성할 수 있는 범용 Factory를 만듭니다. 타입 안정성이 보장되어 런타임 에러를 방지합니다.


10. Builder Pattern vs Factory

개요

Factory 패턴과 자주 비교되는 Builder 패턴입니다. 복잡한 객체를 단계적으로 생성할 때는 Builder가 더 적합합니다.

코드 예제

class CarBuilder {
  private car = { brand: '', model: '', color: '' };

  setBrand(brand: string) {
    this.car.brand = brand;
    return this;
  }

  setModel(model: string) {
    this.car.model = model;
    return this;
  }

  build() { return this.car; }
}

const car = new CarBuilder()
  .setBrand('Tesla')
  .setModel('Model 3')
  .build();

설명

메서드 체이닝으로 단계적으로 객체를 구성합니다. Factory는 한 번에 객체를 생성하지만, Builder는 복잡한 객체를 가독성 좋게 만들 수 있습니다.


11. Factory with Validation

개요

Factory 패턴에 유효성 검증 로직을 추가하여 잘못된 객체 생성을 방지합니다. 도메인 규칙을 강제할 수 있습니다.

코드 예제

class EmailFactory {
  static create(email: string) {
    const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

    if (!isValid) {
      throw new Error('Invalid email format');
    }

    return {
      email,
      send: (msg: string) => console.log(`Sending: ${msg}`)
    };
  }
}

const email = EmailFactory.create('user@example.com');
email.send('Hello!'); // Sending: Hello!

설명

객체 생성 전에 유효성 검증을 수행합니다. 잘못된 데이터로 객체가 생성되는 것을 원천 차단하여 시스템 안정성을 높입니다.


12. Real World API Client Factory

개요

실무에서 자주 사용하는 API 클라이언트 Factory 예제입니다. 환경에 따라 다른 설정의 클라이언트를 생성합니다.

코드 예제

class ApiClientFactory {
  static create(env: 'dev' | 'prod') {
    const baseURL = env === 'prod'
      ? 'https://api.example.com'
      : 'http://localhost:3000';

    return {
      baseURL,
      get: (path: string) =>
        fetch(`${baseURL}${path}`).then(r => r.json())
    };
  }
}

const client = ApiClientFactory.create('dev');
// client.get('/users').then(console.log);

설명

환경에 따라 다른 설정의 HTTP 클라이언트를 생성합니다. 개발/운영 환경 전환이 쉽고, 클라이언트 코드는 환경을 신경 쓰지 않아도 됩니다.


마치며

이번 글에서는 Factory Pattern 디자인 패턴 완벽 가이드에 대해 알아보았습니다. 총 12가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.

관련 태그

#TypeScript #FactoryPattern #DesignPattern #ObjectCreation #SoftwareArchitecture

#TypeScript#FactoryPattern#DesignPattern#ObjectCreation#SoftwareArchitecture

댓글 (0)

댓글을 작성하려면 로그인이 필요합니다.

함께 보면 좋은 카드 뉴스

마이크로서비스 배포 완벽 가이드

Kubernetes를 활용한 마이크로서비스 배포의 핵심 개념부터 실전 운영까지, 초급 개발자도 쉽게 따라할 수 있는 완벽 가이드입니다. 실무에서 바로 적용 가능한 배포 전략과 노하우를 담았습니다.

Application Load Balancer 완벽 가이드

AWS의 Application Load Balancer를 처음 배우는 개발자를 위한 실전 가이드입니다. ALB 생성부터 ECS 연동, 헬스 체크, HTTPS 설정까지 실무에 필요한 모든 내용을 다룹니다. 초급 개발자도 쉽게 따라할 수 있도록 단계별로 설명합니다.

고객 상담 AI 시스템 완벽 구축 가이드

AWS Bedrock Agent와 Knowledge Base를 활용하여 실시간 고객 상담 AI 시스템을 구축하는 방법을 단계별로 학습합니다. RAG 기반 지식 검색부터 Guardrails 안전 장치, 프론트엔드 연동까지 실무에 바로 적용 가능한 완전한 시스템을 만들어봅니다.

에러 처리와 폴백 완벽 가이드

AWS API 호출 시 발생하는 에러를 처리하고 폴백 전략을 구현하는 방법을 다룹니다. ThrottlingException부터 서킷 브레이커 패턴까지, 실전에서 바로 활용할 수 있는 안정적인 에러 처리 기법을 배웁니다.

AWS Bedrock 인용과 출처 표시 완벽 가이드

AWS Bedrock의 Citation 기능을 활용하여 AI 응답의 신뢰도를 높이는 방법을 배웁니다. 출처 추출부터 UI 표시, 검증까지 실무에서 바로 사용할 수 있는 완전한 가이드입니다.