我正在尝试保存向量并使用 undo 方法通过使用备忘录模式来恢复向量,但它不起作用。看守者.java:
import java.util.*;
public class Caretaker {
private Vector <Memento> undoList= new Vector<Memento>();
public Caretaker() {}
public void saveMyClass(MyClass mc){
undoList.add(new Memento(mc));
}
public void undo(){
undoList.lastElement().restore();
undoList.remove(undoList.lastElement());
}
}
备忘录.java:
public class Memento {
private MyClass myclass;
private Vector mState;
public Memento(MyClass mc) {
this.myclass=mc;
mState=mc.state;
}
public void restore()
{
myclass.state=this.mState;
}
}
MyClass.java:
public class MyClass {
Vector state=new Vector<>();
public MyClass() {
}
public Vector getState(){
return state;
}
public void doAction(int i){
state.add(i);
}
}
TestMemento.java:
public static void main(String args[]) {
Caretaker ct = new Caretaker();
MyClass mc = new MyClass();
System.out.println("Create a my class object with state 1");
System.out.println("Current state : " + mc.getState());
ct.saveMyClass(mc);
mc.doAction(3);
System.out.println("Change my class object to state 2");
System.out.println("Current state : " + mc.getState());
ct.saveMyClass(mc);
mc.doAction(5);
System.out.println("Change my class object to state 3");
System.out.println("Current state : " + mc.getState());
ct.saveMyClass(mc);
mc.doAction(7);
System.out.println("Change my class object to state 4");
System.out.println("Current state : " + mc.getState());
ct.undo();
System.out.println("Perform undo");
System.out.println("Current state : " + mc.getState());
ct.undo();
System.out.println("Perform undo");
System.out.println("Current state : " + mc.getState());
}
}
结果:
Current state : []
Change my class object to state 2
Current state : [3]
Change my class object to state 3
Current state : [3, 5]
Change my class object to state 4
Current state : [3, 5, 7]
Perform undo
Current state : [3, 5, 7]
Perform undo
Current state : [3, 5, 7]
因此,我更喜欢在撤消后更改为之前的状态。但它不起作用。在同样的情况下,我已将 Vector 更改为 int 状态
public void doAction(){
state++;
}
然后我可以得到结果
Create my class object with state 1
Current state : 0
Change my class object to state 2
Current state: 1
Change my class object to state 3
Current state: 2
Change my class object to state 4
Current state : 3
Perform undo
Current state: 2
Perform undo
Current state: 1