코드의 효율성과 재사용성을 높이기 위해서 디자인 패턴은 필수다!
Creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
가구 공장을 운영한다고 가정해 보자. 우리의 가구 공장은 의자를 판매하고 있으며 총 세개의 사이즈 (Big, Medium, Small)의 의자를 생산한다.
의자는 높이, 넓이, 깊이의 세가지 특징을 가지고, 각 사이즈마다 이 값은 다르다.
그렇다면 우리 공장은 클라이언트가 의자를 주문하면 주문한 사이즈에 맞는 의자를 생산하는 공정을 설계해야 할 것이다.
이러한 실생활의 예는 객체지향 언어에서도 그대로 적용 할 수 있다.
(어차피 코드라는게 실생활의 반영이니까)
먼저 이를 UML로 표현하면,
우리의 예제에서는 Button interface가 Chair가 된다.
이를 코드로 표현하면,
from abc import ABCMeta, abstractstaticmethod
class IChair(metaclass = ABCMeta):
@abstractstaticmethod
def get_dimensions():
""" Chair Interface """
class BigChair(IChair):
def __init__(self):
self.height = 80
self.width = 80
self.depth = 80
def get_dimensions(self):
return {
"height" : self.height,
"width" : self.width,
"depth" : self.width
}
class MediumChair(IChair):
def __init__(self):
self.height = 70
self.width = 70
self.depth = 70
def get_dimensions(self):
return {
"height" : self.height,
"width" : self.width,
"depth" : self.width
}
class SmallChair(IChair):
def __init__(self):
self.height = 60
self.width = 60
self.depth = 60
def get_dimensions(self):
return {
"height" : self.height,
"width" : self.width,
"depth" : self.width
}
class ChairFactory():
@staticmethod
def get_chair(chairtype):
try:
if chairtype == "BigChair":
return BigChair()
elif chairtype == "MediumChair":
return MediumChair()
elif chairtype == "SmallChair":
return SmallChair()
raise AssertionError("Chair not Found")
except AssertionError as _e:
print(e)
if __name__ == "__main__":
Chair = ChairFactory.get_chair("SmallChair")
print(Chair.get_dimensions())
output: {'height': 60, 'width': 60, 'depth': 60}
from __future__ import annotations
from abc import ABC, abstractmethod
class Creator(ABC):
"""
The Creator class declares the factory method that is supposed to return an
object of a Product class. The Creator's subclasses usually provide the
implementation of this method.
"""
@abstractmethod
def factory_method(self):
"""
Note that the Creator may also provide some default implementation of
the factory method.
"""
pass
def some_operation(self) -> str:
"""
Also note that, despite its name, the Creator's primary responsibility
is not creating products. Usually, it contains some core business logic
that relies on Product objects, returned by the factory method.
Subclasses can indirectly change that business logic by overriding the
factory method and returning a different type of product from it.
"""
# Call the factory method to create a Product object.
product = self.factory_method()
# Now, use the product.
result = f"Creator: The same creator's code has just worked with {product.operation()}"
return result
"""
Concrete Creators override the factory method in order to change the resulting
product's type.
"""
class ConcreteCreator1(Creator):
"""
Note that the signature of the method still uses the abstract product type,
even though the concrete product is actually returned from the method. This
way the Creator can stay independent of concrete product classes.
"""
def factory_method(self) -> ConcreteProduct1:
return ConcreteProduct1()
class ConcreteCreator2(Creator):
def factory_method(self) -> ConcreteProduct2:
return ConcreteProduct2()
class Product(ABC):
"""
The Product interface declares the operations that all concrete products
must implement.
"""
@abstractmethod
def operation(self) -> str:
pass
"""
Concrete Products provide various implementations of the Product interface.
"""
class ConcreteProduct1(Product):
def operation(self) -> str:
return "{Result of the ConcreteProduct1}"
class ConcreteProduct2(Product):
def operation(self) -> str:
return "{Result of the ConcreteProduct2}"
def client_code(creator: Creator) -> None:
"""
The client code works with an instance of a concrete creator, albeit through
its base interface. As long as the client keeps working with the creator via
the base interface, you can pass it any creator's subclass.
"""
print(f"Client: I'm not aware of the creator's class, but it still works.\n"
f"{creator.some_operation()}", end="")
if __name__ == "__main__":
print("App: Launched with the ConcreteCreator1.")
client_code(ConcreteCreator1())
print("\n")
print("App: Launched with the ConcreteCreator2.")
client_code(ConcreteCreator2())
출처: https://refactoring.guru/design-patterns/
복잡해보이지만 차근히 본다면 간단하다.
각 Creator는 Creator(추상)
를 상속받아 method를 overide한다. 각 Product는 Product(추상)
을 상속받아 overide한다.
오버라이드를 통해 객체를 커스텀 할 수 있고 추상클래스에 default 설정도 가능하다.