Factory Method Pattern (Creational Pattern)
팩토리 메서드 패턴 (Factory Method Pattern):
팩토리 패턴의 확장판이다.
팩토리 패턴에서는 팩토리 클래스가 객체를 생성하는 역할을 담당했다면,
팩토리 메서드 패턴에서는 팩토리 클래스가 객체를 생성하는 역할을 서브 클래스에게 위임한다.
또한 서브 클래스(컨크리트 팩토리) 클래스에서 추가적인 기능을 제공할 수 있음
Factory Method Pattern의 작동방식
팩토리 메서드 패턴은 객체 생성을 위한 인터페이스를 정의하고,
서브 클래스에서 각각의 다른방식으로 객체를 생성하도록 한다.
예시)
팩토리 메서드 패턴을 사용하여, 강아지와 고양이를 생성하는 것을 생각해봦,
우선, 팩토리 인터페이스를 정의한다.
해당 인터페이스는 동물 생성이라는 공통의 메서드를 갖고있다.
이제 이 인터페이스를 구현하는 서브 클래스(강아지 팩토리, 고양이 팩토리)를 정의한다.
각각의 서브 클래스는 동물 생성 메서드를 오버라이딩하여,
각각의 서브 클래스에서 동물을 생성하도록 한다.
이제, 클라이언트는 팩토리 인터페이스를 통해 동물을 생성하도록 한다.
Factory Method Pattern 구현
팩토리 메서드 패턴을 구현하기 위해서는 다음과 같은 요소들이 필요하다.
- 팩토리 인터페이스
- 팩토리 구현 클래스
- 생성될 프로덕트 인터페이스
- 생성될 프로덕트 구현 클래스
- 팩토리를 사용하는 클라이언트
class Product: # Product
def use(self):
pass
class IDCard(Product): # ConcreteProduct
def __init__(self, owner):
print(owner + "의 카드를 만듭니다.")
self.owner = owner
def use(self):
print(self.owner + "의 카드를 사용합니다.")
class Factory: # Factory
def create(self, owner) -> Product:
prod = self.createProduct(owner)
self.registerProduct(prod)
return prod
def createProduct(self, owner) -> Product:
pass
def registerProduct(self, product):
pass
class IDCardFactory(Factory): # ConcreteFactory
def __init__(self):
self.owners = [] # 생성된 IDCard의 owner를 저장하는 리스트
def createProduct(self, owner) -> Product:
return IDCard(owner)
def registerProduct(self, product):
self.owners.append(product.owner)
myFactory = IDCardFactory()
card1 = myFactory.create("황빵")
card2 = myFactory.create("빵빵이")
card3 = myFactory.create("고탱이")
card1.use()
card2.use()
card3.use()
728x90
반응형
'Dev > DesignPattern' 카테고리의 다른 글
[DesignPattern] Singleton Pattern (0) | 2023.04.25 |
---|---|
[DesignPattern] Builder Pattern (0) | 2023.04.25 |
[DesignPattern] Abstract Factory Pattern (0) | 2023.04.25 |
[DesignPattern] Factory Pattern (0) | 2023.04.24 |
[DesignPattern] SOLID Principle (4) | 2023.04.24 |