Thanks for your help guys. At the end of the day it came down to my complete misunderstanding about how Java works. I was under the impression (for some strange reason) that creating a Command
and giving it my object meant that it received a copy instead of a reference to the original. If that was the case then calling .execute()
in a Command
would have had no effect on the object outside of the class.
Yet, I found that this was not the case after creating a small test:
Sprite.java:
public class Sprite {
private int x;
Sprite(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
Command.java:
public interface Command {
void execute();
}
MoveLeftCommand.java:
public class MoveLeftCommand implements Command {
private Sprite s;
MoveLeftCommand(Sprite s) {
this.s = s;
}
public void execute() {
s.setX(s.getX() - 1);
}
}
MoveRightCommand.java:
public class MoveRightCommand implements Command {
private Sprite s;
MoveRightCommand(Sprite s) {
this.s = s;
}
public void execute() {
s.setX(s.getX() + 1);
}
}
Test.java:
import java.lang.*;
import java.util.*;
public class Test
{
public static void main(String[] args) {
Sprite mario = new Sprite(0);
Command command = null;
Map<String, Command> commands = new HashMap<String, Command>();
commands.put("a", new MoveLeftCommand(mario));
commands.put("d", new MoveRightCommand(mario));
// Test...
System.out.println(mario.getX()); // 0
command = (Command) commands.get("a");
command.execute();
System.out.println(mario.getX()); // -1
command.execute();
System.out.println(mario.getX()); // -2
command = (Command) commands.get("d");
command.execute();
System.out.println(mario.getX()); // -1
}
}
I correctly saw 0 -1 -2 -1 in the console, just as I would have in C++.