Java - Memento模式和撤消

时间:2013-12-04 11:16:14

标签: java design-patterns memento

我正在实现一个撤消/重做功能,这需要我使用纪念模式。

部分程序的流程:“...程序然后使用Memento Pattern存储上一个Vector,然后新创建的对象将被添加到Vector。之后,用户可以选择show命令来显示什么是在Vector内部,他也可以输入undo命令进行恢复,撤消可以重复,直到恢复到原始状态......“

根据我的研究,我知道会有创作者,纪念品和看护人。

这是我的看护人计划

public class CareTaker {
      private Memento m;
      private Stack s;
      private Vector v;
      // Some of the implementation are not shown

      public void create() {
            // Some of the implementation are not shown
            // Assuming Vector is named "v"
            // Passing Vector to memento
            m = new Memento(v);
            s.add(m);
      }
      public void undo() {
          v = s.pop().restore();
      }
}
public class Memento {
    private Vector _v;
    public Memento(Vector v) {
      _v = v;
    }
    public Vector restore() {
      return _v;
    }
}

不幸的是,我没有确定“发起人”,也不知道会是哪一个。 如果没有Originator,这个代码片段是否是正确的Memento模式?

1 个答案:

答案 0 :(得分:4)

memento模式用于保存对象的状态,而不知道它的内部数据结构。

我尝试用Iterator示例

解释它
public class MementoListIterator<E> implements Iterator<E> {

    public static class Memento {

        private int savedIndex;

        private Memento(MementoListIterator<?> mementoListIterator) {
            this.savedIndex = mementoListIterator.index;
        }

    }

    private List<E> elements;

    private int index = 0;

    public MementoListIterator(List<E> elements) {
        this.elements = elements;
    }

    public Memento save() {
        return new Memento(this);

    }

    public void restore(Memento memento) {
        this.index = memento.savedIndex;
    }

    @Override
    public boolean hasNext() {
        return this.index < elements.size();
    }

    @Override
    public E next() {
        return elements.get(index++);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Not implemented yet");
    }
}

客户端现在可以保存迭代器的任何状态,而不知道迭代器如何在内部管理它的状态。

public class Main {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("A", "B", "C", "D", "E");
        MementoListIterator<String> mementoListIterator = new MementoListIterator<String>(
                list);

        Memento initialState = mementoListIterator.save();

        while (mementoListIterator.hasNext()) {
            String string = mementoListIterator.next();
            System.out.println(string);
        }
                    // Normally we can not re-use the iterator, but
                    // fortuanatly we saved the initial state.

        // restore the initial state and we can use the Iterator again
        mementoListIterator.restore(initialState);

        while (mementoListIterator.hasNext()) {
            String string = mementoListIterator.next();
            System.out.println(string);
        }
    }
}