gpt4 book ai didi

java - 使用带参数的命令模式

转载 作者:搜寻专家 更新时间:2023-11-01 02:01:56 26 4
gpt4 key购买 nike

我有一个像这样的 ReloadableWeapon 类:

public class ReloadableWeapon {

private int numberofbullets;

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

public void attack(){
numberofbullets--;
}

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

具有以下接口(interface):

public interface Command {
void execute();
}

然后像这样使用它:

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

客户:

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

我想知道,对于命令pattern,在我看到的示例中,除了命令作用于的对象之外,没有其他参数 .

This example, alters the execute method to allow for a parameter .

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

在命令 pattern 中包含参数是否是不好的做法/代码味道,在本例中是带有项目符号数量的 constructor

最佳答案

我不认为将参数添加到execute 会是糟糕的设计或违反命令模式。

这完全取决于您希望如何使用命令对象:单例或原型(prototype)范围。

如果使用 Prototype 作用域,则可以在构造函数方法中传递命令参数。每个命令实例都有自己的参数。

如果您使用单例范围(共享/重用实例),则可以在执行方法中传递命令参数。对于这种情况,命令的单例应该是线程安全的。这个解决方案也是 IoC/DI 框架的 friend 。

关于java - 使用带参数的命令模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43872241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com