[英]Is there a better/cleaner way to conditionally create a type than using instanceof? [Java]
Suppose I have: 假设我有:
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>(); // /!\
}
The problem is MobileSuitCollection is an Interface, so I can't instantiate it. 问题是MobileSuitCollection是一个接口,所以我无法实例化它。 For example, I could do: 例如,我可以这样做:
MobileSuitCollection temporaryCollection = new GundamMeisterCollection<MobileSuitso>();
MobileSuitCollection temporaryCollection = new InnovatorCollection<MobileSuitso>();
MobileSuitCollection temporaryCollection = new CannonFolderCollection<MobileSuitso>();
etc. However, to manipulate temporaryCollection
, I need it to be of the same type as the one passed via parameter to my Class. 但是,要操作temporaryCollection
,我需要它与通过参数传递给我的类的类型相同。 So I thought about doing this: 所以我想这样做:
if (msCollection instanceof GundamMeisterCollection) {
...
} else if (msCollection instanceof InnovatorCollection) {
...
} ...
I realize that is awful however. 我意识到这很糟糕。 Is there a better way to do this? 有一个更好的方法吗? Would it be possible to keep a reference to the class used by the initial type and then instantiate the temporaryCollection
with that? 是否可以保留对初始类型使用的类的引用,然后用它实例化temporaryCollection
?
The code that you place in the if-clause can be placed in a Visitor
: 您放在if子句中的代码可以放在一个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
}
and then let MobileSuitCollection
have a method: 然后让MobileSuitCollection
有一个方法:
void visit(MobileSuitCollectionVisitor visitor);
And in each implementation of MobileSuitCollection
simply have 而在MobileSuitCollection
每个实现中都有
public void visit(MobileSuitCollectionVisitor visitor) {
visitor.handleCollection(this);
}
A quick and dirty way to do it would be to clone the original collection, then manipulate it as needed. 快速而肮脏的方法是克隆原始集合,然后根据需要进行操作。 A better way might be to add a newInstance()
method to the interface, or pass in a factory to FightingZone
. 更好的方法可能是在接口中添加newInstance()
方法,或者将工厂传递给FightingZone
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.