가정하자 내가 가지고있는 다음과 같은 인터페이스와 구현이 같은getClass
interface Weapon{
int attack();
}
public class Sword implements Weapon {
//Constructor, and Weapon interface implementation
//...
public void wipeBloodfromSword(){}
}
public class ChargeGun implements Weapon {
//Constructor, and Weapon interface implementation
//...
public void adjustlasersight(){}
}
하고이를 저장 :
List<Weapon> weaponInventory = new ArrayList<Weapon>();
weaponInventory.add(new Sword());
weaponInventory.add(new ChargeGun());
문제 :
그들이 List<Weapon>
에 저장되어 있다고 가정하면 나는 분명히에 선언 된 메소드에만 액세스 할 수 있습니다.interface
. downcasting
이고 instanceof/getClass()
의 사용을 피해야하는 경우 클래스 특정 방법 wipeBloodfromSword()
및 adjustlasersight()
에 액세스하려면 어떻게해야합니까?
가능한 해결 방법 :
공격 메서드가 호출 된 후, 나는이처럼 내 인터페이스를 다시 쓰기 전에 행동이 있다는 것을 감안할 때 :
interface Weapon{
//Can reload a weapon, adjust a laser sight
//do anything to the weapon to prepare for an attack
void prepareWeapon();
int attack();
//Not sure of a more proper name,
//but you can wipe blood off sword or take off silencer
void postAttackActions();
}
동안, 나는에있어 이 취미 프로젝트를 제어하면 interface
을 변경할 수없는 상황이 발생할 수 있으며 interface
은이 특정 문제를 해결할 수 있습니다. interface
을 그대로 두어야한다면 어떻게해야합니까?
"어떻게해야합니까?"라는 질문은 좋은 유형이 아닙니다. –
인터페이스를 변경할 수 없다면 * instanceof 또는 reflection을 사용해야합니다. 그러나 정답은 인터페이스를 변경하는 것입니다. –
정적 클래스가 정답이 아닙니까 ??? –