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 that MobileSuitCollection is an interface, so I cannot create it. For example, I could do:

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

etc .. However, in order to manipulate temporaryCollection, I need it to be of the same type as the one that went through the parameter to my class. So I thought about this:

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

I understand that this is terrible. Is there a better way to do this? Is it possible to save a reference to the class used by the initial type, and then create an instance temporaryCollectionwith this?

+3
source share
2 answers

, 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);
}
+2

, . newInstance() factory FightingZone.

0

Source: https://habr.com/ru/post/1752352/


All Articles