Using a command template with parameters

I have a ReloadableWeapon class as follows:

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 this:

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);
    }
}

Cilento:

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

I was interested, with the team pattern, with the examples that I saw, there are no others besides the object on which the team acts parameters.

This example modifies the execute method to enable the parameter .

Another example, closer to what I have here, with parameters in the constructor .

Is it a bad experience / smell code to include parameters in a team pattern, in this case constructorwith the number of bullets?

+4
source share
4 answers

- , .

, , : "", gun bullets=10.

, , bullets , , .

, , . ReloadWeaponCommand bullets. (, Strategy) .

-1

, execute .

, Command Object: Singleton Or Prototype scope.

, . .

( / ), execute. . IoC/DI.

+7

, 95 , 9 10 1 5 . Invoker, invoker , . . , invoker , , .

, Invoker . , wiki, " , "

0

" ", " ".
, , , .
- . , . , Control From Top Down to Bottom Up - , , ...

.

, - , .

. @Loc IMO, , , , , (, , ), . @Loc, " " " ", - , , ; ( ) . " , ".

, . , . , , I.e. "" , , , - , , .

, . . @Loc " ", , , , " ".

, . . , , . . Iterator Visitor , , , .
. - , .

, , , . , (int items) ( , ), , ; . factory, , ; , , .

Not that anyone here has done this, but I find it especially interesting if someone suggests that it is normal to ignore or ignore a certain motivation for any established design template (especially GoF). If you need to change the GoF design template, you are using the wrong one. Just say

PS if you absolutely need to, why don't you use a template solution instead, and not intentionally change the specific interface design;

0
source

Source: https://habr.com/ru/post/1676761/


All Articles