Created
August 5, 2019 14:10
-
-
Save njofce/f4ea5324cb188a44f4814e229339c703 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CommandManager { | |
private static CommandManager instance = null; | |
private QueueStack<List<Action>> queueStackNormal; | |
private QueueStack<List<Action>> queueStackReverse; | |
private List<String> actionHistory; | |
static CommandManager getInstance(){ | |
if(instance != null) | |
return instance; | |
return new CommandManager(); | |
} | |
private CommandManager() { | |
queueStackNormal = new QueueStack<>(); | |
queueStackReverse = new QueueStack<>(); | |
actionHistory = new ArrayList<>(); | |
} | |
void execute(List<Action> actionList){ | |
actionList.forEach(Action::execute); | |
queueStackNormal.push(actionList); | |
actionList.forEach(a -> actionHistory.add(a.getName())); | |
} | |
void undo() { | |
Optional<List<Action>> optionalActions = queueStackNormal.pop(); | |
optionalActions.ifPresent(aList -> { | |
aList.forEach(Action::undo); | |
queueStackReverse.push(aList); | |
aList.forEach(a -> actionHistory.add(a.getName() + " - undo")); | |
}); | |
} | |
void redo() { | |
Optional<List<Action>> optionalActions = queueStackReverse.pop(); | |
optionalActions.ifPresent(aList -> { | |
aList.forEach(Action::execute); | |
queueStackNormal.push(aList); | |
aList.forEach(a -> actionHistory.add(a.getName() + " - redo")); | |
}); | |
} | |
void clearNormal() { | |
queueStackNormal.clear(); | |
} | |
void clearReverse() { | |
queueStackReverse.clear(); | |
} | |
List<String> getActionHistory() { | |
return actionHistory; | |
} | |
public static void main(String[] args) { | |
CommandManager manager = CommandManager.getInstance(); | |
List<Action> actionList = new ArrayList<>(); | |
actionList.add(new Action1("Action 1")); | |
actionList.add(new Action2("Action 2")); | |
System.out.println("===ACTIONS==="); | |
manager.execute(actionList); | |
manager.undo(); | |
manager.redo(); | |
manager.clearNormal(); | |
manager.undo(); | |
manager.redo(); | |
System.out.println("===HISTORY==="); | |
System.out.println(manager.getActionHistory().toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment