I am trying to save the vector and use undo method to restore the vector by using a memento pattern, but it is not working. Caretaker.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());
}
}
Memento.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());
}
}
Result:
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]
As the result, I prefer will change to the previous state after undo. But it is not working. In the same situation, I have changed the Vector to int state
public void doAction(){
state++;
}
Then I can get the result
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