package class8_3_PhonebookCommands_start;//package pbook; import java.util.Stack; public class History { // doneCmds: those commands that are currently executed // undoneCmds: commands which were undone protected Stack doneCmds = new Stack<>(), undoneCmds = new Stack<>(); // returns null if no command to undo, the command otherwise public Command nextToUndo() { if ( doneCmds.isEmpty() ) return null; else return doneCmds.peek(); } // returns null if no command to redo, the command otherwise public Command nextToRedo() { if ( undoneCmds.isEmpty() ) return null; else return undoneCmds.peek(); } // execute command and store it on the done commands list; // old undone commands are permanently deleted public void doCommand(Command new_cmd) { new_cmd.execute(); undoneCmds.clear(); doneCmds.push(new_cmd); } // undoes last executed command; precondition: at least one command to undo public void undo() { Command to_undo = doneCmds.pop(); to_undo.unexecute(); undoneCmds.push(to_undo); } // redoes last undone command; precondition: at least one command to redo public void redo() { Command todo = undoneCmds.pop(); todo.execute(); doneCmds.push(todo); } }