mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-05-15 20:59:07 +00:00
add redo function on command pattern
This commit is contained in:
@@ -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";
|
||||
|
||||
Reference in New Issue
Block a user