我已经实现了使用命令模式撤消/重做添加数字的功能,如下所示:
public void start(Stage stage) {
try {
CommandManager command = new CommandManager();
command.addCommand(new CommandChanger("2"));
command.undo();
command.redo();
}
}
这正确撤消和重做2.但是,如何使用JavaFX按钮单击执行此操作?
供参考,这是我的CommandManager类:
public class CommandManager {
private Node currentIndex = null;
private Node parentNode = new Node();
public CommandManager(){
currentIndex = parentNode;
}
public CommandManager(CommandManager manager){
this();
currentIndex = manager.currentIndex;
}
public void clear(){
currentIndex = parentNode;
}
public void addCommand(Command command){
Node node = new Node(command);
currentIndex.right = node;
node.left = currentIndex;
currentIndex = node;
}
public boolean canUndo(){
return currentIndex != parentNode;
}
public boolean canRedo(){
return currentIndex.right != null;
}
public void undo(){
//validate
if ( !canUndo() ){
throw new IllegalStateException("Cannot undo. Index is out of range.");
}
//undo
currentIndex.command.undo();
//set index
moveLeft();
}
private void moveLeft(){
if ( currentIndex.left == null ){
throw new IllegalStateException("Internal index set to null.");
}
currentIndex = currentIndex.left;
}
private void moveRight(){
if ( currentIndex.right == null ){
throw new IllegalStateException("Internal index set to null.");
}
currentIndex = currentIndex.right;
}
public void redo(){
//validate
if ( !canRedo() ){
throw new IllegalStateException("Cannot redo. Index is out of range.");
}
//reset index
moveRight();
currentIndex.command.redo();
}
private class Node {
private Node left = null;
private Node right = null;
private final Command command;
public Node(Command c){
command = c;
}
public Node(){
command = null;
}
}
}