팩토리 패턴(Factory Pattern)은 객체 생성 로직을 별도의 팩토리 클래스/메서드에 위임하는 생성 패턴이다. 클라이언트는 구체적인 클래스를 알 필요 없이 인터페이스를 통해 객체를 생성한다.
세 가지 변형
| 종류 | 설명 |
|---|
| 단순 팩토리 | 조건에 따라 다른 객체 반환 |
| 팩토리 메서드 | 서브클래스가 생성 방식 결정 |
| 추상 팩토리 | 연관된 객체 군을 생성 |
python
from abc import ABC, abstractmethod
# 제품 인터페이스
class Animal(ABC):
@abstractmethod
def speak(self) -> str: pass
class Dog(Animal):
def speak(self): return "Woof!"
class Cat(Animal):
def speak(self): return "Meow!"
# 팩토리 메서드 패턴
class AnimalFactory(ABC):
@abstractmethod
def create_animal(self) -> Animal: pass
def make_sound(self) -> str:
animal = self.create_animal()
return animal.speak()
class DogFactory(AnimalFactory):
def create_animal(self) -> Animal:
return Dog()
class CatFactory(AnimalFactory):
def create_animal(self) -> Animal:
return Cat()
# 단순 팩토리 (정적)
class SimpleAnimalFactory:
@staticmethod
def create(animal_type: str) -> Animal:
factories = {"dog": Dog, "cat": Cat}
cls = factories.get(animal_type)
if not cls:
raise ValueError(f"Unknown animal: {animal_type}")
return cls()
factory = SimpleAnimalFactory.create("dog")
print(factory.speak()) # Woof!
java
// UI 컴포넌트 추상 팩토리
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
class WindowsFactory implements GUIFactory {
public Button createButton() { return new WindowsButton(); }
public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}
class MacFactory implements GUIFactory {
public Button createButton() { return new MacButton(); }
public Checkbox createCheckbox() { return new MacCheckbox(); }
}
장단점
| 장점 | 단점 |
|---|
| 결합도 감소 | 클래스 수 증가 |
| 개방-폐쇄 원칙 준수 | 코드 복잡성 증가 |
| 테스트 용이 | 단순한 경우 과설계 |
관련 개념