mirror of
https://github.com/jlengrand/design-patterns.git
synced 2026-03-10 08:11:17 +00:00
Add undo capability
This commit is contained in:
@@ -4,4 +4,5 @@ public interface Command {
|
||||
|
||||
void execute();
|
||||
|
||||
void undo();
|
||||
}
|
||||
|
||||
@@ -5,4 +5,9 @@ public class EmptyCommand implements Command{
|
||||
public void execute() {
|
||||
System.out.println("No Command");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void undo() {
|
||||
System.out.println("No Command undo");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,4 +14,9 @@ public class LightOff implements Command {
|
||||
public void execute() {
|
||||
light.off();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void undo() {
|
||||
light.on();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,4 +14,10 @@ public class LightOn implements Command {
|
||||
public void execute() {
|
||||
light.on();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void undo() {
|
||||
light.off();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,13 +8,20 @@ import java.util.Map;
|
||||
public class RemoteControl {
|
||||
|
||||
private Map<String, Command> commands = new HashMap<>();
|
||||
private Command lastCommand = new EmptyCommand();
|
||||
|
||||
public void addCommand(String commandName, Command command){
|
||||
commands.put(commandName, command);
|
||||
}
|
||||
|
||||
public void pressCommand(String commandName){
|
||||
commands.getOrDefault(commandName, new EmptyCommand()).execute();
|
||||
Command command = commands.getOrDefault(commandName, new EmptyCommand());
|
||||
command.execute();
|
||||
lastCommand = command;
|
||||
}
|
||||
|
||||
public void undo(){
|
||||
lastCommand.undo();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -33,6 +40,10 @@ public class RemoteControl {
|
||||
|
||||
System.out.println(rc);
|
||||
rc.pressCommand("BathroomLightOn");
|
||||
rc.undo();
|
||||
rc.pressCommand("BathroomLightOff");
|
||||
rc.undo();
|
||||
rc.undo();
|
||||
rc.pressCommand("Null check");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user