add redo function on command pattern

This commit is contained in:
jack.zhang
2015-04-15 11:47:25 +08:00
parent 33566805ee
commit 120555f740
6 changed files with 46 additions and 4 deletions
+18 -3
View File
@@ -1,8 +1,12 @@
package com.iluwatar;
import java.util.Deque;
import java.util.LinkedList;
public class Wizard extends Target {
private Command previousSpell;
private Deque<Command> undoStack = new LinkedList<>();
private Deque<Command> redoStack = new LinkedList<>();
public Wizard() {
setSize(Size.NORMAL);
@@ -12,16 +16,27 @@ public class Wizard extends Target {
public void castSpell(Command command, Target target) {
System.out.println(this + " casts " + command + " at " + target);
command.execute(target);
previousSpell = command;
undoStack.offerLast(command);
}
public void undoLastSpell() {
if (previousSpell != null) {
if (!undoStack.isEmpty()) {
Command previousSpell = undoStack.pollLast();
redoStack.offerLast(previousSpell);
System.out.println(this + " undoes " + previousSpell);
previousSpell.undo();
}
}
public void redoLastSpell() {
if (!redoStack.isEmpty()) {
Command previousSpell = redoStack.pollLast();
undoStack.offerLast(previousSpell);
System.out.println(this + " redoes " + previousSpell);
previousSpell.redo();
}
}
@Override
public String toString() {
return "Wizard";