Java设计模式之备忘录模式

备忘录模式(Memento Pattern)是一种行为型设计模式,它允许在不暴露对象内部状态的情况下捕获和恢复对象的内部状态。该模式通过在对象之外保存和恢复对象的状态,使得对象可以在需要时回滚到之前的状态。

在备忘录模式中,有三个核心角色:

  1. 发起人(Originator):它是需要保存状态的对象。它可以创建一个备忘录对象,用于保存当前状态,并可以使用备忘录对象恢复其状态。
  2. 备忘录(Memento):它是保存发起人对象状态的对象。备忘录对象提供一个接口,允许发起人对象访问其内部状态(或者在某些情况下,允许其他对象访问)。
  3. 管理者(Caretaker):它负责保存和恢复备忘录对象。管理者对象可以存储多个备忘录对象,并在需要时将其提供给发起人对象。

下面是一个示例,展示了如何使用备忘录模式来保存和恢复发起人对象的状态。假设我们有一个文本编辑器,用户可以输入文本并进行撤销操作。

// 发起人(Originator)
class TextEditor {
    private String text;

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public TextEditorMemento save() {
        return new TextEditorMemento(text);
    }

    public void restore(TextEditorMemento memento) {
        this.text = memento.getText();
    }
}

// 备忘录(Memento)
class TextEditorMemento {
    private String text;

    public TextEditorMemento(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

// 管理者(Caretaker)
class TextEditorHistory {
    private Stack<TextEditorMemento> history = new Stack<>();

    public void push(TextEditorMemento memento) {
        history.push(memento);
    }

    public TextEditorMemento pop() {
        return history.pop();
    }
}

// 示例使用
public class Main {
    public static void main(String[] args) {
        TextEditor textEditor = new TextEditor();
        TextEditorHistory history = new TextEditorHistory();

        // 编辑文本
        textEditor.setText("Hello, World!");

        // 保存状态
        history.push(textEditor.save());

        // 修改文本
        textEditor.setText("Hello, Java!");

        // 保存状态
        history.push(textEditor.save());

        // 恢复到之前的状态
        textEditor.restore(history.pop());
        System.out.println(textEditor.getText());  // 输出: Hello, Java!

        textEditor.restore(history.pop());
        System.out.println(textEditor.getText());  // 输出: Hello, World!
    }
}

在上面的示例中,TextEditor 是发起人角色,它保存了文本编辑器的状态,并提供了保存和恢复状态的方法。TextEditorMemento 是备忘录角色,它保存了发起人对象的状态。TextEditorHistory 是管理者角色,它保存了多个备忘录对象,并提供了保存和恢复备忘录的方法。通过使用备忘录模式,我们可以在文本编辑器中保存多个状态,并在需要时恢复到之前的状态。

推荐一个ChatGPT使用渠道:点击直达
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值