소프트웨어에 대한 모든 것

[디자인패턴][Prototype] 프로토타입 패턴 본문

시스템 설계 및 디자인/디자인 패턴

[디자인패턴][Prototype] 프로토타입 패턴

앤테바 2022. 3. 24. 14:55
반응형

프로식 패턴 정의

프로토타입 패턴은 cloing을 통해서 존재하는 오브젝트 기반으로 오브젝트를 생성합니다. 프로토타입 패턴은 객체 생성에 비용, 시간, 리소스가 많이 필요하고 이미 유사한 객체가 있는 경우에 사용됩니다. 따라서 이 패턴은 원본 객채를 새 객체에 복사한 다음 필요에 따라 수정하는 메커니즘을 제공합니다.

프로토타입 패턴 장점

  • sub-classing을 줄임
  • 객체 생성의 복잡성을 숨김
  • 클라이언트는 어떤 유형의 객체가 될지 알지 못해도 새 객체를 얻을 수 있음
  • 런타임에 객체를 추가하거나 제거할 수 있음

비용이 많이 드는 데이터베이스 작업 후에 특정 객체가 생성된다고 칩시다. 이 작업이 반복 요청이 발생하고 중복적인 객체 생성에 많은 비용이 들어갑니다. 그렇다면 생성된 객체를 캐시하고 다음 요청이 발생하는 복제본을 반환하고 필요한 경우 데이터베이스를 업데이트하여 데이터베이스 호출을 줄일 수 있습니다.

프로토타입 패턴 클래스 다이어그램

Prototype 패턴 Class Diagram

프로토타입 패턴 활용

추상 클래스 Shape, Shape을 상속 받은 Rectangle/Square/Circle가 있습니다. ShapeCache를 통해서 shape을 caching하고 있다가 사용자의 요청이 오면 즉시 복제본을 만들어서 제공하는 예시 코드를 살펴 보겠습니다.

 

"""
https://en.proft.me/2016/09/27/prototype-design-pattern-java-and-python/
"""
import copy
from abc import ABC, abstractmethod


class Shape(ABC):
    def __init__(self):
        self.id = None
        self.type = None

    @abstractmethod
    def draw(self):
        pass

    def clone(self):
        return copy.copy(self)


class Rectangle(Shape):
    def __init__(self):
        super().__init__()
        self.type = 'Rectangle'

    def draw(self):
        print('Rectangle.draw() method')


class Square(Shape):
    def __init__(self):
        super().__init__()
        self.type = 'Square'

    def draw(self):
        print(f'{self.type}.draw() method')


class Circle(Shape):
    def __init__(self):
        super().__init__()
        self.type = 'Circle'

    def draw(self):
        print(f'{self.type}.draw() method')


class ShapeCache:
    cache = {}

    @staticmethod
    def get_shape(sid):
        shape = ShapeCache.cache.get(sid, None)
        return shape.clone()

    @staticmethod
    def load():
        circle = Circle()
        circle.id = '1'
        ShapeCache.cache[circle.id] = circle

        square = Square()
        square.id = '2'
        ShapeCache.cache[square.id] = square

        rect = Rectangle()
        rect.id = '3'
        ShapeCache.cache[rect.id] = rect


ShapeCache.load()

circle = ShapeCache.get_shape('1')
circle.draw()

square = ShapeCache.get_shape('2')
square.draw()

rect = ShapeCache.get_shape('3')
rect.draw()

출력 결과

Circle.draw() method
Square.draw() method
Rectangle.draw() method

 

참고 자료:

Prototype design pattern in Java and Python

반응형
Comments