Python 디자인 패턴

Memento Pattern in Python

Memento Pattern in Python을 편집하고 온라인 실행할 수 있는 실용 예제로 학습하세요.

Memento Pattern이란?

Memento Pattern in Python을 편집하고 온라인 실행할 수 있는 실용 예제로 학습하세요.

언제 사용하나요?

  • 검증된 구조로 반복되는 객체 설계 문제를 해결합니다.
  • 책임을 분리하여 코드를 더 쉽게 확장하고 테스트할 수 있게 합니다.
  • 팀에서 아키텍처를 논의할 때 공통 설계 용어를 사용합니다.

예제 코드

코드 실행 →
main.py
from dataclasses import dataclass


@dataclass(frozen=True)
class Snapshot:
    # Memento: store a restorable snapshot without exposing internals.
    text: str


class Editor:
    def __init__(self): self.text = ""
    def save(self): return Snapshot(self.text)

    def restore(self, snapshot):
        # Restore state without exposing representation details.
        self.text = snapshot.text


editor = Editor()
editor.text = "draft"
saved = editor.save()
editor.text = "changed"
editor.restore(saved)
print(editor.text)

예상 출력

draft

작동 원리

이 예제는 Memento Pattern in Python을 보여 줍니다. 입력값을 바꾸어 코드의 동작을 확인하세요.

값을 변경하고 Python 설치 없이 CodeUtility 온라인 Python 컴파일러에서 실행하세요.

연습 문제

입력값과 경계 조건을 바꾸고 더 큰 데이터에서도 동작을 확인하세요.

  1. 패턴 구조를 유지하면서 예제 도메인을 바꿔 보세요.
  2. 패턴을 더 단순한 구현과 비교하고 장단점을 설명하세요.
  3. 다른 구현을 추가하기 전에 각 참여 요소에 대한 테스트를 작성하세요.
Python IDE에서 실행 →