假设我有以下界面和实现:
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>
中,我显然只能访问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
该怎么办?
答案 0 :(得分:2)
由于你有一组固定的类,你可以使用访问者模式,它可以在没有明确的向下转发的情况下工作。
class WeaponVisitor {
void visit(Sword aSword) { }
void visit(ChargeGun aGun) { }
}
// add accept method to your Weapon interface
interface Weapon {
...
void accept(Visitor v);
}
// then implement accept in your implementing classes
class Sword {
...
@Override
void accept(Visitor v) {
v.visit(this); // this is instanceof Sword so the right visit method will be picked
}
}
// lastly, extend Visitor and override the methods you are interested in
class OnlySwordVisitor extends Visitor {
@Override void visit(Sword aSword) {
System.out.println("Found a sword!");
aSword.wipeBloodfromSword();
}
}
答案 1 :(得分:-1)
您可以将您的列表项目输入到Sword或ChargeGun,然后调用相应的方法
((Sword) weaponInventory.get(0)).wipeBloodfromSword();