banner
Oct 3, 2023
130 Views

Memento pattern

Written by
banner

Memento (Memento Design Pattern) là một mẫu thiết kế phần mềm tiết lộ trạng thái nội bộ riêng tư của một đối tượng. Một ví dụ về cách mẫu này có thể được sử dụng là để khôi phục một đối tượng về trạng thái trước đó của nó (hoàn tác thông qua việc quay trở lại), một ví dụ khác là phiên bản hóa, và một ví dụ khác là tuỳ chỉnh hóa đối tượng thành dạng dữ liệu.

The memento pattern is a software design pattern that exposes the private internal state of an object. One example of how this can be used is to restore an object to its previous state (undo via rollback), another is versioning, another is custom serialization.

Ví dụ bạn làm 1 phần mềm chỉnh sửa văn bản và làm chức năng undo-redo

class TextEditor:
    def __init__(self):
        self.content = ""

    def write_text(self, text):
        self.content += text

    def get_snapshot(self):
        return TextEditorMemento(self.content)

    def restore_snapshot(self, memento):
        self.content = memento.get_state()

    def __str__(self):
        return self.content


class TextEditorMemento:
    def __init__(self, state):
        self.state = state

    def get_state(self):
        return self.state


class TextEditorHistory:
    def __init__(self):
        self.snapshots = []

    def push(self, snapshot):
        self.snapshots.append(snapshot)

    def pop(self):
        if self.snapshots:
            return self.snapshots.pop()
        else:
            return None


if __name__ == "__main__":
    editor = TextEditor()
    history = TextEditorHistory()

    editor.write_text("Hello, ")
    history.push(editor.get_snapshot())

    editor.write_text("world!")
    history.push(editor.get_snapshot())

    print("Current Content:", editor)

    # Undo
    snapshot = history.pop()
    if snapshot:
        editor.restore_snapshot(snapshot)
    print("After Undo:", editor)

    # Redo
    snapshot = history.pop()
    if snapshot:
        editor.restore_snapshot(snapshot)
    print("After Redo:", editor)
Article Categories:
blockchain · dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *