mardi 9 mai 2017

Using the Command Pattern with Parameters

I have a ReloadableWeapon class like this:

public class ReloadableWeapon {
    //keeping the design really simple, took out weapon logic.
    private int numberofbullets;

    public ReloadableWeapon(int numberofbullets){
        this.numberofbullets = numberofbullets;
    }

    public void attack(){
        numberofbullets--;
    }

    public void reload(int reloadBullets){
        this.numberofbullets += reloadBullets;
    }
}

with the following interface:

public interface Command {
    void execute();
}

and use it like so:

public class ReloadWeaponCommand implements Command {

    private int reloadBullets;
    private ReloadableWeapon weapon;

    //Is is okay to specify the number of bullets?
    public ReloadWeaponCommand(ReloadableWeapon weapon, int bullets){
        this.weapon = weapon;
        this.reloadBullets = bullets;
    }

    @Override
    public void execute() {
        weapon.reload(reloadBullets);
    }
}

Cilent:

    ReloadableWeapon chargeGun = new ReloadableWeapon(10);
    Command reload = new ReloadWeaponCommand(chargeGun,10);
    ReloadWeaponController controlReload = new ReloadWeaponController(reload);
    controlReload.executeCommand();

I was wondering, with the command pattern, with the examples I've seen, other than the object that the command is acting on, there are no other parameters. This example, alters the execute method to allow for a parameter.

Is it bad practice/code smell to include parameters in the command pattern, in this case the constructor with the number of bullets?

Aucun commentaire:

Enregistrer un commentaire