」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 理解 Java 中的 Memento 設計模式

理解 Java 中的 Memento 設計模式

發佈於2024-08-07
瀏覽:677

Understanding the Memento Design Pattern in Java

問題

Memento 模式解決了在不違反物件封裝的情況下擷取和復原物件內部狀態的需求。這在您想要實現撤消/重做功能、允許物件恢復到先前狀態的場景中非常有用。

解決方案

Memento 模式涉及三個主要組成部分:

  1. Originator:需要保存和恢復內部狀態的物件。
  2. 備忘錄: 儲存發起者內部狀態的物件。紀念品是不可變的。
  3. Caretaker:負責請求發起者從備忘錄中保存或恢復其狀態。

發起者建立一個包含其目前狀態快照的備忘錄。然後,管理員可以儲存該備忘錄,並在需要時用於恢復發起者的狀態。

優點和缺點

優點

  • 保留封裝:允許保存和復原物件的內部狀態,而不暴露其實作細節。
  • 簡單撤消/重做: 方便實現撤消/重做功能,使系統更加健壯和用戶友好。
  • 狀態歷史記錄: 允許維護物件先前狀態的歷史記錄,從而實現不同狀態之間的導航。

缺點

  • 記憶體消耗:儲存多個備忘錄可能會消耗大量內存,特別是當物件的狀態很大時。
  • 額外的複雜性: 為程式碼帶來了額外的複雜性,需要管理紀念品的創建和復原。
  • 管理員職責:管理員需要有效管理紀念品,這會增加系統的責任和複雜性。

實際應用範例

Memento 模式的實際範例是提供撤銷/重做功能的文字編輯器。文件的每次變更都可以儲存為備忘錄,允許使用者根據需要恢復到文件之前的狀態。

Java 中的範例程式碼

代碼中的備忘錄模式:

// Originator
public class Editor {
    private String content;

    public void setContent(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public Memento save() {
        return new Memento(content);
    }

    public void restore(Memento memento) {
        content = memento.getContent();
    }

    // Memento
    public static class Memento {
        private final String content;

        public Memento(String content) {
            this.content = content;
        }

        private String getContent() {
            return content;
        }
    }
}

// Caretaker
public class History {
    private final Stack history = new Stack();

    public void save(Editor editor) {
        history.push(editor.save());
    }

    public void undo(Editor editor) {
        if (!history.isEmpty()) {
            editor.restore(history.pop());
        }
    }
}

// Client code
public class Client {
    public static void main(String[] args) {
        Editor editor = new Editor();
        History history = new History();

        editor.setContent("Version 1");
        history.save(editor);
        System.out.println(editor.getContent());

        editor.setContent("Version 2");
        history.save(editor);
        System.out.println(editor.getContent());

        editor.setContent("Version 3");
        System.out.println(editor.getContent());

        history.undo(editor);
        System.out.println(editor.getContent());

        history.undo(editor);
        System.out.println(editor.getContent());
    }
}
版本聲明 本文轉載於:https://dev.to/diegosilva13/understanding-the-memento-design-pattern-in-java-2c72?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3