我正在实现一个撤销/重做函数,它要求我使用memento模式。
部分程序的流程:"...the程序然后使用Memento模式存储以前的向量,然后将新创建的对象添加到向量中。之后,用户可以选择一个显示命令来显示向量内部的内容,他还可以输入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;
}
}不幸的是,我没有确定“发起人”的身份,也不知道哪个人会是谁。如果没有发起人,这个代码片段是否曾经是一个正确的Memento模式?
发布于 2013-12-04 11:36:18
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);
}
}
}https://stackoverflow.com/questions/20373876
复制相似问题