gpt4 book ai didi

java - 接口(interface)、类和代码味道

转载 作者:行者123 更新时间:2023-11-30 10:29:56 25 4
gpt4 key购买 nike

假设我有以下接口(interface):

public interface GameObject {
void viewDetails();
}

public interface Weapon extends GameObject {
void attack();
}

//A weapon is not the only item reloadable. A container could be refilled.
public interface Reloadable extends GameObject {

void replenish (final int amount);
}

和实现:

public final class ReloadableWeapon implements  Reloadable, Weapon {


private String weaponName;
private int numberofbullets;

public ReloadableWeapon(String name, int bullets){

this.weaponName = name;
this.numberofbullets = bullets;
}


@Override
public void replenish(final int amount) {
this.numberofbullets = amount;
}

@Override
public void attack() {
System.out.println(this.weaponName + " fired");
this.numberofbullets--;
System.out.println("Shots Left: " + this.numberofbullets);
}


@Override
public void viewDetails() {
System.out.println(this.weaponName);

}
}

在 Effective Java 中,其中一章建议我应该通过 interface 声明我的类。我了解这些优点,但如果我有多个 interface 怎么办?

在我的主要方法中,我这样声明它:

ReloadableWeapon chargeGun = new ReloadableWeapon("ChargeGun",10);

并像这样使用它:

public static void reloadGameWeapon(Reloadable reload){
reload.replenish(10);
}

public static void attackGameWeapon(Weapon toAttackwith){
toAttackwith.attack();
}

如果我通过interface声明它,我显然只会得到特定接口(interface)提供的方法。我可以创建另一个名为 ReloadedableWeapon 的 interface,但那里需要放置哪些方法?我如何声明使用我的 ReloadableWeapon 不好的做法或代码味道?

最佳答案

您可以创建一个同时扩展WeaponReloadable 的接口(interface)。

public interface WeaponReloadable extends Weapon,Reloadable {
...
}

有了这个实现:

public final class MyWeaponReloadable implements  WeaponReloadable  {
...
}

通过这种方式,您可以创建一个使用 ReloadableWeapon 接口(interface)声明的 MyReloadableWeapon 实例,并将其传递到具有 Reloadable 的方法中武器参数:

WeaponReloadable weaponReloadable = new MyWeaponReloadable();
reloadGameWeapon(weaponReloadable);
attackGameWeapon(weaponReloadable);

关于java - 接口(interface)、类和代码味道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820751/

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