我有一个像这样的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;
}
}
Run Code Online (Sandbox Code Playgroud)
以下内容interface:
public interface Command {
void execute();
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Cilent:
ReloadableWeapon chargeGun = new ReloadableWeapon(10);
Command reload = new ReloadWeaponCommand(chargeGun,10);
ReloadWeaponController controlReload = new ReloadWeaponController(reload);
controlReload.executeCommand();
Run Code Online (Sandbox Code Playgroud)
我想知道,使用命令pattern,我看到的例子,除了命令所作用的对象,没有其他的parameters.
在命令中包含参数是不好的做法/代码气味pattern,在这种情况下constructor是子弹的数量?
我不认为在执行中添加参数会是糟糕的设计或违反命令模式.
这完全取决于您希望如何使用Command Object: Singleton或Prototype范围.
如果使用Prototype范围,则可以在Constructor方法中传递命令参数.每个命令实例都有自己的参数.
如果使用Singleton作用域(共享实例),则可以在execute方法中传递命令参数.对于这种情况,命令的单例应该是线程安全的.该解决方案也是IoC/DI框架的朋友.