Jun*_*mer 2 java design-patterns memento
我正在实现一个撤消/重做功能,它需要我使用备忘录模式。
部分程序的流程:“...程序然后使用Memento Pattern存储之前的Vector,然后将新创建的对象添加到Vector。之后,用户可以选择show命令来显示Vector内部的内容,他也可以输入undo命令来恢复,可以重复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 模式?
备忘录模式用于在不知道对象内部数据结构的情况下保存对象的状态。
我试着用一个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);
        }
    }
}
| 归档时间: | 
 | 
| 查看次数: | 2012 次 | 
| 最近记录: |