【发布时间】:2017-10-07 21:47:17
【问题描述】:
我有一个这样的 ReloadableWeapon 类:
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;
}
}
使用以下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,对于我所看到的示例,除了命令所作用的对象之外,没有其他parameters。
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 带有项目符号数?
【问题讨论】:
-
命令模式只是说有一个对象封装了执行命令所需的所有信息,例如参数。就像在 Wikipedia 页面上一样:“此信息包括方法名称、拥有该方法的对象和方法参数的值。”如果您不能包含任何数据,那将是一个非常无用的模式:/
-
@DaveNewton - 基本上,wiki 是说可以在构造函数中传递子弹数量以重新加载命令?如果我理解正确的话。
标签: java oop design-patterns