jeudi 17 septembre 2015

What is the best way to navigate a complex tree of dissimilar objects?

For example:

class Vehicle {
    Collection<Axle> axles;
}

class Axle {
    Collection<Wheel> wheels;
}

class Wheel {
    // I think there are dually rims that take two tires -- just go with it
    Collection<Tire> tires;
}

class Tire {
    int width;
    int diameter;
}

I have a service through which I can get a collection of all Vehicle objects I know about. Now say I have a tire of a specific width and diameter, and I want to find a Vehicle which can take it. The simplistic way is to have a set of four nested loops, like so:

for (Vehicle vehicle : vehicles) {
    for (Axle axle : vehicle.getAxles()) {
        for (Wheel wheel : axle.getWheels()) {
            for (Tire tire : wheel.getTires()) {
                if (tire.width == targetWidth
                 && tire.diameter == targetDiameter) {
                    // do something
                    break;
                }
            }
        }
    }
}

Is there a good design pattern for this? Or a better data structure to use? Would it be better to just keep an index somewhere of tire information mapped to vehicles?

Aucun commentaire:

Enregistrer un commentaire