java - 有没有比使用 instanceof 更好/更干净的方法来有条件地创建类型? [ java ]

标签 java design-patterns oop instanceof

假设我有:

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 是一个接口(interface),所以我无法实例化它。例如,我可以这样做:

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

最佳答案

您放在 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
}

然后让 MobileSuitCollection 有一个方法:

void visit(MobileSuitCollectionVisitor visitor);

并且在 MobileSuitCollection 的每个实现中都有

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

关于java - 有没有比使用 instanceof 更好/更干净的方法来有条件地创建类型? [ java ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3144759/

相关文章:

java - 创建 jar 文件后数据库连接失败

java - 斯坦福 CoreNLP (Java) 中的浅解析与深度解析

java - 使用 MVC 风格,调用查询函数的最佳位置在哪里?

c# - 设计模式场景——我应该使用哪个?

javascript - 探索 MooTools 中的实现/扩展

java - 如何在 powershell 脚本或 cmd 中设置 java 程序中的 keystore 路径?

java - 对 Java 包和 Windows 目录感到困惑吗?

java - 是否有任何好的 J2EE 值列表处理程序模式实现?

c++ - C++是否使用接口(interface)?

c# - 参数 Action<T1, T2, T3> 其中 T3 可选