[python] 팩토리 메서드 패턴

팩토리 메서드 패턴은 객체 생성을 처리하는 디자인 패턴 중 하나입니다. 팩토리 메서드 패턴을 사용하면 객체를 생성하는 부분을 서브 클래스로 분리할 수 있습니다. 이를 통해 클래스의 인스턴스화를 캡슐화하고 유연성을 높일 수 있습니다.

팩토리 메서드 패턴의 구성 요소

  1. Creator (생성자): 객체를 생성하는 인터페이스를 정의합니다. 실제 객체 생성은 이 인터페이스를 상속받은 ConcreteCreator 클래스가 담당합니다.
  2. Product (제품): 생성자로 생성되는 객체의 추상 클래스입니다. 구체적인 제품은 이 추상 클래스를 상속받아 구현합니다.
  3. ConcreteProduct (구체적인 제품): Product 클래스를 상속받아 실제 객체를 만드는 클래스입니다.
  4. Client (클라이언트): ConcreteCreator와 ConcreteProduct 클래스를 사용하여 객체를 생성하는 역할을 합니다.

예시 코드

from abc import ABC, abstractmethod

class Creator(ABC):
    @abstractmethod
    def factory_method(self):
        pass

    def some_operation(self):
        product = self.factory_method()
        # Product를 사용하는 코드 작성

class ConcreteCreator1(Creator):
    def factory_method(self):
        return ConcreteProduct1()

class ConcreteCreator2(Creator):
    def factory_method(self):
        return ConcreteProduct2()

class Product(ABC):
    @abstractmethod
    def operation(self):
        pass

class ConcreteProduct1(Product):
    def operation(self):
        # 구체적인 제품1에 대한 동작 정의
        pass

class ConcreteProduct2(Product):
    def operation(self):
        # 구체적인 제품2에 대한 동작 정의
        pass

위의 예시 코드에서 Creator 클래스는 factory_method()라는 팩토리 메서드를 정의하고 있습니다. 이 메서드는 Product 타입의 객체를 반환합니다.

ConcreteCreator1과 ConcreteCreator2는 Creator 클래스를 상속받아 factory_method()를 구체적으로 구현합니다. 이는 Product를 상속받은 구체적인 제품 객체를 생성하고 반환하는 역할을 합니다.

Product 클래스는 operation()이라는 추상 메서드를 정의하고 있습니다. 이 메서드는 구체적인 제품 클래스에서 구현됩니다.

구체적인 제품 클래스인 ConcreteProduct1과 ConcreteProduct2는 Product를 상속받아서 operation()을 구현합니다.

Client는 ConcreteCreator1과 ConcreteCreator2를 사용하여 객체를 생성하고, 생성된 객체의 operation()을 호출하여 사용하는 역할을 수행합니다.

팩토리 메서드 패턴의 장점

팩토리 메서드 패턴은 객체 생성에 관련된 복잡한 로직을 캡슐화하여 유연하고 확장 가능한 코드를 작성하는 데 도움을 줍니다. 이 패턴을 적절히 활용하면 객체 지향 프로그래밍에서 유지보수성과 재사용성을 향상시킬 수 있습니다.

참고 자료