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 that I know of. Now say that I have a tire of a certain width and diameter, and I want to find a vehicle that can take it. The simplest way is to have a set of four nested loops, for example:
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 template for this? Or is it better to use a data structure? Would it be better to just keep the index somewhere in the tire information displayed on vehicles?
edit : answers to questions from comments
Do you have control over the structure of the data you receive from the service?
Yes
Do you need to look for different tires many times in the same data?
Yes
Is performance a problem?
Not particularly
When you find a tire, you just need to know which car contains it, or do you also need an axle and a wheel?
Sometimes just a vehicle, sometimes just an axis - two different contexts
Do you need a link to the found tire?
Yes, in cases where I need an axis
edit2 : Extending the metaphor further to explain the two contexts above:
Context 1 - I want to know the vehicle, so I can send an employee to collect the car and return it.
Context 2 - I want to know the axis and the tire because I am in a car trying to get the job done.
java loops design-patterns
Sam jones
source share