模式介绍

备忘录模式是一种行为型设计模式,它允许在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便以后当需要时能将该对象恢复到原先保存的状态。

使用场景

  • 当需要保存对象在某一时刻的状态时
  • 当直接获取对象的状态会暴露实现细节时
  • 当需要实现撤销/重做功能时

代码示例

// 备忘录类
public class Memento {
    private String state;

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

    public String getState() {
        return state;
    }
}

// 发起人
public class Originator {
    private String state;

    public void setState(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }

    public Memento createMemento() {
        return new Memento(state);
    }

    public void restoreFromMemento(Memento memento) {
        state = memento.getState();
    }
}

// 管理者
public class Caretaker {
    private List mementos = new ArrayList<>();

    public void add(Memento memento) {
        mementos.add(memento);
    }

    public Memento get(int index) {
        return mementos.get(index);
    }
}

优缺点

优点

  • 可以创建对象状态的快照
  • 简化了发起人
  • 实现了信息的封装

缺点

  • 如果状态数据很大,会消耗较多内存
  • 管理者必须跟踪发起人的生命周期
  • 可能会产生大量的备忘录对象