HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
객체 지향 프로그래밍
객체 지향 프로그래밍
/
디자인 패턴
디자인 패턴
/
🏭
Factory Method Pattern
🏭

Factory Method Pattern

Motivation

팩토리 메서드 패턴은 객체 생성에대한 인터페이스만을 제공하고 구체타입에 대한 결정은 Subclasses에게 위임한다.
호텔은 Real-life 팩토리 메서드 패턴의 예시이다. 내가 돈을 호텔 프론트 데스크에 내면 프론트 직원이 방의 열쇄를 준다. 그사람이 Room Factory이다. ???

Intent

  • 객체 생성에대한 Interface 정의. Subclass가 구체 타입을 정해서 Instantiate 하게 하기

Implementation

notion image
Product - 제품
ConcreteProduct - 구체 제품
Factory - 공장 → 제품을 찍어내는 factoryMethod를 가짐
ConcreteFactory - 구체 공장
Code Example
위의 예시에서 다른 구체클래스를 생성하는 공장을 만들어내고 싶으면 다른 구체 팩토리클래스를 구현해야한다.
 
추상클래스로 정의된 팩토리도 보면 Product에만 의존하고 전혀 구체 Product에는 의존하지 않는다.

Applicablity

  • 클래스가 생성해야 하는 구체 타입을 예상할 수 없을 때

Examples

 

Specific problems & Implementation

Creator 클래스 정의
  • 팩토리 메소드 패턴을 적용하고 싶은데 팩토리 클래스가 이미 정의 되어 있는 경우
      1. 추상 클래스로 정의 되어 있을 때
      1. 구체 클래스로 정의 되어 있을 때
       
팩토리 메소드 패턴은 팩토리 패턴의 특이 케이스임
 
 

Pros and Cons

Pros
      Cons
      • 공장의 제품은 같은 인터페이스를 가져야함
       
      interface Product { } abstract class Factory { protected abstract Product factoryMethod(); } class ConcreteProduct implements Product { } class ConcreteFactory extends Factory { protected Product factoryMethod() { return new ConcreteProduct(); } } public class Client { public static void main(String[] args) { Factory creator = new ConcreteFactory(); Product product = creator.factoryMethod(); System.out.println(product.getClass().getSimpleName()); } }
      ConcreteProduct Process finished with exit code 0
      public Document CreateDocument(String type){ if (type.isEqual("html")) return new HtmlDocument(); if (type.isEqual("proprietary")) return new MyDocument(); if (type.isEqual("pdf")) return new PdfDocument (); }
      before - 냄세나는 if 문이 덕지덕지 나열되어 있다.
      public void NewDocument(String type){ Document doc=CreateDocument(type); docs.add(doc); }
      After -