例如:
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; }
我有一项服务,通过它我可以获得我所知道的所有车辆对象的集合.现在说我有一个特定宽度和直径的轮胎,我想找到一辆可以接受它的车辆.简单的方法是有一组四个嵌套循环,如下所示:
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; } } } } }
这有一个好的设计模式吗?还是要使用更好的数据结构?将某个指数保留在映射到车辆的轮胎信息的位置会更好吗?
编辑:回答评论中的问题
Do you have control over the structure of the data you receive from the service?
是
Do you need to search for different tires multiple times in the same data?
是
Is performance an issue?
不是特别
When you find the tire,do you just need to know which vehicle contains it or do you also need the axle and wheel?
有时只是车辆,有时只是车轴 – 两种不同的环境
Do you need the reference to the tire that was found?
是的,在我需要轴的情况下
EDIT2:
进一步扩展隐喻,解释上述两种情况:
背景1 – 我想知道车辆,所以我可以派一名工人去收集车辆并将其带回来
背景2 – 我想知道轴和轮胎,因为我正在尝试做这项工作的车辆
解决方法
您可以使用
Java 8 streams来展平循环.
vehicles.stream() .flatMap(vehicle -> vehicle.getAxles().stream()) .flatMap(axle -> axle.getWheels().stream()) .flatMap(wheel -> wheel.getTires().stream()) .filter(tire -> tire.width == targetWidth && tire.diameter == targetDiameter) .forEach(tire -> { // do something });
关于流的好处是你可以在序列中的任何地方插入额外的过滤器,过滤器,findAny等等.