Java – Memento模式和撤消

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

部分程序的流程:“…然后程序使用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模式?

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

我尝试用Iterator示例来解释它

 public class MementoListIterator implements Iterator { public static class Memento { private int savedIndex; private Memento(MementoListIterator mementoListIterator) { this.savedIndex = mementoListIterator.index; } } private List elements; private int index = 0; public MementoListIterator(List 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 list = Arrays.asList("A", "B", "C", "D", "E"); MementoListIterator mementoListIterator = new MementoListIterator( 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); } } }