IT/SW Dev.

디자인 패턴(Design Patterns) - 생성 패턴의 주요 유형(싱글톤, 팩토리 메서드, 프로토타입 등)

부티형 2025. 3. 5. 21:54
반응형

생성 패턴(Creational Patterns)

생성 패턴은 객체의 생성 방식과 초기화를 캡슐화하여 객체 생성 과정에서 발생하는 문제를 해결하는 디자인 패턴이다. 객체의 생성 과정을 보다 유연하고 효율적으로 관리할 수 있도록 돕는다.


🔹 생성 패턴의 주요 유형

1. 싱글톤 패턴(Singleton Pattern)

  • 특정 클래스의 인스턴스를 오직 하나만 생성하도록 보장하는 패턴
  • 전역적인 접근점을 제공하여 어디서든 동일한 인스턴스를 사용 가능

사용 사례: 데이터베이스 연결 객체, 설정 관리 객체, 로깅 시스템

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

# 사용 예시
s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # True (동일한 객체)

반응형

2. 팩토리 메서드 패턴(Factory Method Pattern)

  • 객체 생성을 서브클래스에서 결정하도록 하는 패턴
  • 객체 생성을 위한 인터페이스를 제공하되, 실제 객체 생성은 하위 클래스에서 수행

사용 사례: 데이터베이스 드라이버, UI 컴포넌트 생성

from abc import ABC, abstractmethod

# 제품(객체) 인터페이스 정의
class Product(ABC):
    @abstractmethod
    def use(self):
        pass

# 구체적인 제품 클래스
class ConcreteProductA(Product):
    def use(self):
        return "Using Product A"

class ConcreteProductB(Product):
    def use(self):
        return "Using Product B"

# 팩토리 클래스
class Factory(ABC):
    @abstractmethod
    def create_product(self):
        pass

# 구체적인 팩토리 클래스
class ConcreteFactoryA(Factory):
    def create_product(self):
        return ConcreteProductA()

class ConcreteFactoryB(Factory):
    def create_product(self):
        return ConcreteProductB()

# 사용 예시
factory = ConcreteFactoryA()
product = factory.create_product()
print(product.use())  # Using Product A

3. 추상 팩토리 패턴(Abstract Factory Pattern)

  • 관련 객체들을 그룹화하여 생성하는 팩토리의 팩토리
  • 서로 연관된 객체들의 생성을 한 곳에서 관리할 수 있도록 함

사용 사례: GUI 테마(윈도우/맥 스타일 UI), 데이터베이스 연결 객체

from abc import ABC, abstractmethod

# 버튼 인터페이스
class Button(ABC):
    @abstractmethod
    def render(self):
        pass

# 구체적인 버튼 클래스
class WindowsButton(Button):
    def render(self):
        return "Windows Button"

class MacOSButton(Button):
    def render(self):
        return "MacOS Button"

# GUI 팩토리 인터페이스
class GUIFactory(ABC):
    @abstractmethod
    def create_button(self):
        pass

# 구체적인 팩토리 클래스
class WindowsFactory(GUIFactory):
    def create_button(self):
        return WindowsButton()

class MacOSFactory(GUIFactory):
    def create_button(self):
        return MacOSButton()

# 사용 예시
factory = WindowsFactory()
button = factory.create_button()
print(button.render())  # Windows Button

4. 빌더 패턴(Builder Pattern)

  • 복잡한 객체의 생성을 단계별로 수행할 수 있도록 하는 패턴
  • 생성 과정이 복잡한 경우, 다양한 조합을 쉽게 만들 수 있도록 분리

사용 사례: HTML 문서 생성, 복잡한 객체 구성

class Product:
    def __init__(self):
        self.parts = []

    def add_part(self, part):
        self.parts.append(part)

    def show(self):
        return f"Product Parts: {', '.join(self.parts)}"

# 빌더 클래스
class Builder:
    def __init__(self):
        self.product = Product()

    def add_part_a(self):
        self.product.add_part("Part A")

    def add_part_b(self):
        self.product.add_part("Part B")

    def get_result(self):
        return self.product

# 디렉터 클래스
class Director:
    def construct(self, builder):
        builder.add_part_a()
        builder.add_part_b()
        return builder.get_result()

# 사용 예시
builder = Builder()
director = Director()
product = director.construct(builder)
print(product.show())  # Product Parts: Part A, Part B

5. 프로토타입 패턴(Prototype Pattern)

  • 기존 객체를 복사하여 새로운 객체를 생성하는 패턴
  • 새로운 객체를 만들 때 비용이 많이 드는 경우 유용

사용 사례: 게임 캐릭터 클로닝, 데이터베이스 엔티티 복제

import copy

class Prototype:
    def clone(self):
        return copy.deepcopy(self)

# 구체적인 클래스
class ConcretePrototype(Prototype):
    def __init__(self, value):
        self.value = value

# 사용 예시
prototype = ConcretePrototype("Original")
clone = prototype.clone()
print(clone.value)  # Original
print(prototype is clone)  # False (새로운 객체)

📌 정리

패턴 핵심 개념 사용 사례
싱글톤(Singleton) 하나의 인스턴스만 생성 설정 관리, 로깅, 데이터베이스 연결
팩토리 메서드(Factory Method) 서브클래스가 객체 생성 결정 UI 컴포넌트, 데이터베이스 드라이버
추상 팩토리(Abstract Factory) 관련된 객체 군을 묶어 생성 GUI 테마, 데이터베이스 연결
빌더(Builder) 복잡한 객체를 단계적으로 생성 HTML 생성, 복잡한 데이터 모델
프로토타입(Prototype) 기존 객체를 복제하여 생성 게임 캐릭터 복제, 데이터베이스 엔티티

생성 패턴을 적절히 활용하면 객체 생성 과정이 깔끔해지고 유지보수가 쉬워지며, 코드 재사용성이 높아진다. 🎯

반응형