2010-06-29 55 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

相关问题