2010-06-29 149 views
3

假設我有:有沒有比使用instanceof更好/更簡潔的方式來有條件地創建一個類型? 【JAVA]

public class FightingZone<MobileSuitso, Background> { 

    private MobileSuitCollection<MobileSuitso> msCollection; 
    private BackgroundInfo<Background> bgInfo; 

    public FightingZone(MobileSuitCollection<MobileSuitso> newCollection, BackgroundInfo<Background> newInfo) { 
     this.msCollection = newCollection; 
     this.bgInfo = newInfo; 
    } 

    ... 

     ...// inside a method 
     MobileSuitCollection temporaryCollection = new MobileSuitCollection<MobileSuitso>(); // /!\ 

} 

的問題是MobileSuitCollection是一個接口,所以我不能實例化。例如,我可以這樣做:

MobileSuitCollection temporaryCollection = new GundamMeisterCollection<MobileSuitso>(); 
MobileSuitCollection temporaryCollection = new InnovatorCollection<MobileSuitso>(); 
MobileSuitCollection temporaryCollection = new CannonFolderCollection<MobileSuitso>(); 

等。然而,操控temporaryCollection,我需要的是同一類型的一個通過參數傳遞給我的班。所以我想這樣做的:

if (msCollection instanceof GundamMeisterCollection) { 
    ... 
} else if (msCollection instanceof InnovatorCollection) { 
    ... 
} ... 

我意識到這是可怕的。然而。有一個更好的方法嗎?是否可以保留對初始類型使用的類的引用,然後用那個實例化temporaryCollection

回答

2

您在如果子句中放置的代碼可以放在Visitor

// Generics skipped for brevity 
interface MobileSuitCollectionVisitor { 
    handleCollection(GundamMeisterCollection collection); 
    handleCollection(InnovatorCollection collection); 
    handleCollection(CannonFolderCollection collection) 
} 

class ConcreteVisitor implements MobileSuitCollectionVisitor { 
    // place all of the logic in the implemented methods 
} 

然後讓MobileSuitCollection有一個方法:

void visit(MobileSuitCollectionVisitor visitor); 

而且在MobileSuitCollection每個實現簡單有

public void visit(MobileSuitCollectionVisitor visitor) { 
    visitor.handleCollection(this); 
} 
+0

我正在研究使用反射來獲取類名並從那裏實例化它。假設這是可能的,它會不會使代碼更清潔?或者這仍然是首選方法? – 2010-06-29 21:22:28

+0

如果您要使用反射,請使用類對象而不是類名稱。像這樣:'Class cl = collection.getClass(); Interface inst = cl.newInstance();' – 2010-06-30 03:37:58

+0

反射應該是最後的手段。上述方法是面向對象的方法。 – Bozho 2010-06-30 05:27:05

0

快速和骯髒的方式要做到這一點將克隆原始集合,然後根據需要進行操作。更好的方法可能是將newInstance()方法添加到接口,或者將工廠傳遞到FightingZone

相關問題