Let s say I have a Game class:
Public class Game{
private Board board;
private Stack<Command> commandStack;
//...
//constructor...
//...
Public void createCommamd() {
Command command = new Command(board);
command.exec();
commandStack.push(command);
}
public void undo() {
Command command = commandStack.get(undoRedoPointer);
board = command.unexec();
undoRedoPointer--;
}
public void redo(){
undoRedoPointer++;
Command command = commandStack.get(undoRedoPointer);
command.exec();
}
A Command class that takes a board as a constructor parameter to initialize its field:
public class Command{
private Board board;
private Memento memento;
public Command(Board board){
this.board = board;
}
public void exec(){
memento = new Memento();
memento.setState(board);
board.addColumn(col);
}
public void unexec(){
board = memento.getState();
}
}
And my small memento class that is meant to save the state of board before every change(It kinda back it up):
public class Memento{
private Object boardState;
public Board getState(){
return (Board) boardState;
}
public void setState(Board board){
Object obj = board;
this.boardState = DeepCopy.copy(obj);
}
}
The problem is that my undo method doesn't reset the state of my board in Game to be the one stored in the memento of that particular Command in the Stack. It should be doing it because I set board in Command to be the backupped board in memento, and since board in Command is a reference of board in Game, the latter one should change as well.
I think that this is happening because when I say
board = memento.getState();
I am actually saying that board now points to an another reference, hence it will have no longer anything to do with board in Game.
If my assumption is correct, do you have any idea of how I can make board in Game be like the board backupped in memento?
P.S I have simplified the classes and I hope I could explain my problem decently.
The unexec method should return a board: