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

View File

@ -20,7 +20,17 @@ public class App {
wizard.castSpell(new InvisibilitySpell(), goblin);
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
wizard.undoLastSpell();
goblin.printStatus();
wizard.redoLastSpell();
goblin.printStatus();
wizard.redoLastSpell();
goblin.printStatus();
}
}

View File

@ -11,6 +11,8 @@ public abstract class Command {
public abstract void undo();
public abstract void redo();
@Override
public abstract String toString();

View File

@ -17,6 +17,13 @@ public class InvisibilitySpell extends Command {
}
}
@Override
public void redo() {
if (target != null) {
target.setVisibility(Visibility.INVISIBLE);
}
}
@Override
public String toString() {
return "Invisibility spell";

View File

@ -15,10 +15,17 @@ public class ShrinkSpell extends Command {
@Override
public void undo() {
if (oldSize != null && target != null) {
Size temp = target.getSize();
target.setSize(oldSize);
oldSize = temp;
}
}
@Override
public void redo() {
undo();
}
@Override
public String toString() {
return "Shrink spell";

View File

@ -31,7 +31,8 @@ public abstract class Target {
public abstract String toString();
public void printStatus() {
System.out.println(String.format("%s, size=%s visibility=%s", this,
System.out.println(String.format("%s, [size=%s] [visibility=%s]", this,
getSize(), getVisibility()));
System.out.println();
}
}

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";