I am using Command design pattern :
public abstract class Command {
protected GameObject object;
public Command(GameObject object) {
this.object = object;
}
public abstract void execute();
}
Commands that do something with GameObject extends this class each implementing its execute method.
However, i came to need Command for GameModel class too, and would like it to be also "Command", however i am not sure how to achieve it "pretty" way.
for example, i could do:
public abstract class Command {
protected GameObject object;
protected GameModel model;
public Command(GameObject object) {
this.object = object;
}
public Command(GameModel model){
this.model = model;
}
public abstract void execute();
}
However if i didnt check for null in every execute method, it could eventually throw nullpointer exception, e.g
public class MoveUpCommand extends Command {
public MoveUpCommand(GameObject object) {
super(object);
}
@Override
public void execute() {
((Monster)object).moveUp();
}
}
GameModel model = new GameModel();
Command cmd = new MoveUpCommand(model);
cmd.execute() // nullpointer
and if i wanted to check for null e.g:
public class MoveUpCommand extends Command {
public MoveUpCommand(GameObject object) {
super(object);
}
@Override
public void execute() {
if( object!= null )
((Monster)object).moveUp();
}
}
It would work just fine, however when the command would do nothing, the only thing i could do is to throw exception ( or something indicating that the value is in fact null ).
In C++ there is deleted
constructor, which would indicate such error at compile time, is there some way to simulate it in java? Or is there some design approach for this kind of problem, or am i left to checking for null and throwing exceptions?
Thanks for help!
Aucun commentaire:
Enregistrer un commentaire