Factory Pattern (Creational Pattern)
Factory Pattern 이란?
팩토리 패턴은 객체를 생성에대한 인터페이스를 정의하는 패턴이다
복잡한 객체 생성에 대해서 클라이언트가 관여하지 않도록 한다.
팩토리 패턴은 객체를 생성하는 방법을 캡슐화하여, 객체 생성의 변화에 대응하기 쉽도록 한다.
Factory Pattern의 작동방식
클라이언트가 팩토리에게 A라는 객체 생성을 요청 -> 팩토리는 A라는 객체를 생성하여 클라이언트에게 반환
클라이언트가 팩토리에게 B라는 객체 생성을 요청 -> 팩토리는 B라는 객체를 생성하여 클라이언트에게 반환
Factory Pattern의 구성요소
Creator: 객체를 생성하는 인터페이스나 추상 클래스를 정의합니다.
이 클래스는 객체 생성에 필요한 팩토리 메서드를 포함하고, 이 메서드를 사용하여 객체를 생성합니다.
ConcreteCreator: Creator 클래스를 구현하는 구체 클래스로,
실제 객체 생성을 담당합니다. ConcreteCreator는 팩토리 메서드를 구현하여 특정 객체를 생성하고 반환합니다.
Product: 객체 생성의 결과로 반환되는 인터페이스나 추상 클래스입니다.
생성된 객체는 이 클래스를 구현하거나 상속합니다.
ConcreteProduct: Product 인터페이스나 추상 클래스를 구현하거나 상속하는 클래스로,
실제 생성되는 객체입니다.
Factory Pattern의 구현
class Rabot: # Product
def speak(self):
pass
class Cat(Rabot): # ConcreteProduct
def speak(self):
print("로봇 야옹이 입니다.")
class Dog(Rabot): # ConcreteProduct
def speak(self):
print("로봇 강아지 입니다.")
class Factory: # Creator
def create_robot(self, robot_type):
if robot_type == "cat":
return Cat()
elif robot_type == "dog":
return Dog()
else:
raise Exception("ERROR!! No such robot type")
myFactory = Factory()
firstRobot = myFactory.create_robot("cat")
firstRobot.speak()
secondRobot = myFactory.create_robot("dog")
secondRobot.speak()
Factory Pattern의 영향을 받는 생성패턴들
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 Method Pattern (0) | 2023.04.24 |
[DesignPattern] SOLID Principle (4) | 2023.04.24 |