설계패턴 10. Prototype Pattern

LSDrug·2024년 6월 9일

설계패턴(完)

목록 보기
10/26

Prototype Pattern


1. 개요

프로토타입 패턴은 기존 객체를 복제하여 새로운 객체를 생성하는 바업이다.
그러나 아래의 경우 클래스로부터 인스턴스를 만드는 것이 아니라 인스턴스를 복사해서 새로운 인스턴스를 만드는 것이 좋다.

  • 종류가 너무 많아 클래스로 정리되지 않는 경우
  • 클래스로부터 인스턴스 생성이 어려운 경우
  • framework와 생성하는 인스턴스를 분리하고 싶은 경우

2. 도식화

3. 패턴의 등장인물 정리

  • Prototype(원형)의 역할
    Prototype은 인스턴스를 복사하여 새로운 인스턴스를 만들기 위한 메소드 결정한다.
  • ConcretePrototype(구체적인 원형)의 역할
    ConcretePrototype은 인스턴스를 복사해서 새로운 인스턴스를 만드는 메소드를 실제로 구현
  • Client(이용자)의 역할
    Client는 인스턴스를 복사하는 메소드를 이용해서 새로운 인스턴스를 만든다.

4. 예시

여러가지 형태로 출력이 되는 메소드를 만들어보자.

# Prototype
from abc import *
class Product(metaclass = ABCMeta):

  @abstractmethod
  def use(self):
    pass

  @abstractmethod
  def clone(self):
    pass

# Concrete
class UnderlinePen(Product):
  def use(self, s:str):
    n = len(s)
    print(s)
    for i in range(n):
      print("~", end="")
    print()

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

# Concrete 2
class MessageBox(Product):

  def __init__(self, deco:str):
    self.deco = deco

  def use(self, s:str):
    n = len(s) + 4

    for i in range(n):
      print(self.deco, end="")
    print()
    print(self.deco, s, self.deco)
    for i in range(n):
      print(self.deco, end="")
    print()

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

# Manager
class Manager:

  def __init__(self):
    self.showcase = {"a":1}

  def register(self, name:str, proto:Product):
    self.showcase[name] = proto

  def create(self, protoName):
    p = self.showcase[protoName]
    return p.clone()

# Client
manager = Manager()

m1 = MessageBox("*")
m2 = MessageBox("#")
p1 = UnderlinePen()

manager.register("msg*", m1)
manager.register("msg#", m2)
manager.register("pen", p1)
msg1 = manager.create("msg*")
msg2 = manager.create("msg#")
pen = manager.create("pen")

word = "hello"
msg1.use(word)
word = "world"
msg2.use(word)
pen.use(word)

profile
마약같은 코딩, 마약같은 코딩러

0개의 댓글