[英]If Downcasting Should Be Avoided, What Should I Do?
有以下接口類:
public interface IGameObject {
String gameObjectID();
String gameObjectName();
void isActionValid(String action);
void viewActions();
}
我有以下實現上述接口的抽象類。
package gameprobjectpackage;
public abstract class Weapon implements IGameObject {
//Left out getters/setters to keep it simple
private String gameOjectID;
private String gameObjectName;
private int damage;
public Weapon(String gameOjectID, String gameObjectName,int damage) {
super();
this.gameOjectID = gameOjectID;
this.gameObjectName = gameObjectName;
this.damage = damage;
}
我發現一些帖子表明應該避免向下傾斜。 我理解為什么,但是,我的問題是,如果我需要訪問特定於子類的方法,我該怎么辦。 例如:
public class ChargeGun extends Weapon {
private String [] chargeGunActions;
public ChargeGun(String gameOjectID, String gameObjectName, int damage) {
super(gameOjectID, gameObjectName, damage);
chargeGunActions = new String [3];
chargeGunActions[0] = "Charge and Fire";
chargeGunActions[1] = "Release";
chargeGunActions[2] = "Drop Gun";
}
//This method is only meant for gun, and this type of gun is the only one in my game.
//This method, I don't belive should be in the abstract method weapon, because NOT every weapon is a gun.
public void reloadGun()
{
}
我存儲在一個像這樣的interventory hashmap中:
Map<String,IGameObject> inventory = new HashMap<String,IGameObject>();
當我檢索它時,我將獲得一個IGameObject
,如何正確地投射它,以便我可以訪問ChargeGun
的方法?
您可以使用訪客模式使您免於投射。 這個想法很簡單:你有一個IGameObject的清單,它有一個方法accept(GameObjectVisitor v)直接調用v.visit(this)。 在GameObjectVisitor中,您只需為每個實現實現訪問方法:例如訪問(Chargegun g),訪問(Sword s)等...
換句話說,它就像回旋鏢的原理:GameObjectVisitor調用item.accept(this),而Item實現接受(GameObjectVisitor g)和一個簡單的g.visit(this)。
通過這樣做,訪問者可以為每個實現提供多種訪問方法,並且可以執行特定的操作而無需使用instanceof。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.