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で実行 →