Java 实现嵌套if语句的另一种方法

Java 实现嵌套if语句的另一种方法,java,list,object,if-statement,Java,List,Object,If Statement,我试图重构下面的代码,它使用几个嵌套的if语句来检查两个列表是否包含相同的项 List<Car> CarList = CarService.findCarByConfigtype(pageName); for (int i = 0; i < CarList.size(); i++) { System.out.println(CarRestApiController.data().getModel()); if (CarList.get(i).getModel()

我试图重构下面的代码,它使用几个嵌套的if语句来检查两个列表是否包含相同的项

List<Car> CarList = CarService.findCarByConfigtype(pageName);
for (int i = 0; i < CarList.size(); i++) {
    System.out.println(CarRestApiController.data().getModel());
    if (CarList.get(i).getModel().equals(CarRestApiController.data().getModel())) {
        dataFound.add(CarList.get(i).getModel());
        if (CarList.get(i).getDerivative().equals(CarRestApiController.data().getDerivative())) {
            dataFound.add(CarList.get(i).getDerivative());
            if (CarList.get(i).getSvp().equals(CarRestApiController.data().getSvp())) {
                dataFound.add(CarList.get(i).getSvp());
                if (CarList.get(i).getEngine().equals(CarRestApiController.data().getEngine())) {
                    dataFound.add(CarList.get(i).getEngine());
                    if (CarList.get(i).getFueltype().equals(CarRestApiController.data().getFueltype())) {
                        dataFound.add(CarList.get(i).getFueltype());
                        if (CarList.get(i).getBodystyle().equals(CarRestApiController.data().getBodystyle())) {
                            dataFound.add(CarList.get(i).getBodystyle());
                            if (CarList.get(i).getTransmission().equals(CarRestApiController.data().getTransmission())) {
                                dataFound.add(CarList.get(i).getTransmission());
                                if (CarList.get(i).getSalescategory().equals(CarRestApiController.data().getSalescategory())) {
                                    dataFound.add(CarList.get(i).getSalescategory());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
List CarList=CarService.findCarByConfigtype(pageName);
对于(int i=0;i
我首先将
CarList.get(I)
carrestapiccontroller.data()
的结果保存到@T.J.Crowder建议的变量中。然后我将翻转if检查,并使用
continue
来消除嵌套。像这样:

List<Car> carList = CarService.findCarByConfigtype(pageName);

for (int i = 0; i < carList.size(); i++) {
     Car apiData = CarRestApiController.data();
     Car carListData = carList.get(i);

     System.out.println(CarRestApiController.data().getModel());

     if (!carListData.getModel().equals(apiData.getModel())) {
         continue;
     }
     dataFound.add(carListData.getModel());

     if (!carListData.getDerivative().equals(apiData.getDerivative())) {
         continue;
     }
     dataFound.add(carListData.getDerivative());

     if (!carListData.getSvp().equals(apiData.getSvp())) {
         continue;
     }
     dataFound.add(carListData.getSvp());

     // ... and so on.
 }
List carList=CarService.findCarByConfigtype(pageName);
对于(int i=0;i
一个解决方案可以是使用。为每个if语句制定策略,迭代策略列表并处理列表中的每辆车

public interface CarFeatureStrategy {

    boolean canProcess(Car carToProcess, Car carToMatch);

    Object process(Car carToProcess);
}
canHandle
方法应封装if语句,该语句需要为true才能进行处理,
process
方法应返回汽车相应属性的值(例如,描述中应有8种策略)

CarProcessor
检索与给定
pageName
对应的车辆,从
carrestapiccontroller
检索数据,并使用策略列表处理车辆

public class CarProcessor {


    private CarService carService;
    private CarRestApiController restController;

    private List<CarFeatureStrategy> carFeatureStrategies;

    public void processCars(Object pageName) {
        // for example purpose the list of strategies is initialized here,
        // but it should be initialized somwhere where the initialization is done
        // only once rather than each time the processCars method is called
        carFeatureStrategies = new ArrayList<>();
        carFeatureStrategies.add(new ModelStrategy());
        carFeatureStrategies.add(new DerivativeStrategy());
        carFeatureStrategies.add(new SvpStrategy());
        // ....
        // add to the strategies list an instance of each strategy to process 
        // the car

        Car carToMatch = restController.data();
        List<Car> cars = carService.findCarByConfigtype(pageName);
        List<Object> dataFound = new ArrayList<>();

        for (Car carToProcess : cars) {
            for (CarFeatureStrategy carFeatureStrategy : carFeatureStrategies) {
                if (carFeatureStrategy.canProcess(carToProcess, carToMatch)) {
                    dataFound.add(carFeatureStrategy.process(carToProcess));
                }
            }
        }
    }
}
必须参考链中的下一个战略来加强战略实施

public interface CarFeatureStrategy {

    boolean canProcess(Car carToProcess, Car carToMatch);

    Object process(Car carToProcess);

    CarFeatureStrategy next();
}
public class ModelStrategy implements CarFeatureStrategy {

    private CarFeatureStrategy nextStrategy;

    public ModelStrategy(CarFeatureStrategy nextStrategy) {
        this.nextStrategy = nextStrategy;
    }

    @Override
    public boolean canProcess(Car carToProcess, Car carToMatch) {
        // check only the model
        return carToProcess.getModel().equals(carToMatch.getModel));
    }

    @Override
    public Object process(Car carToProcess) {
        return carToProcess.getModel();
    }

    @Override
    public CarFeatureStrategy next() {
        return this.nextStrategy;
    }
}

public class DerivativeStrategy implements CarFeatureStrategy {

    private CarFeatureStrategy nextStrategy;

    public DerivativeStrategy(CarFeatureStrategy nextStrategy) {
        this.nextStrategy = nextStrategy;
    }

    @Override
    public boolean canProcess(Car carToProcess, Car carToMatch) {
        // check only the derivative property
        return carToProcess.getDerivative().equals(carToMatch.getDerivative());
    }

    @Override
    public Object process(Car carToProcess) {
        return carToProcess.getDerivative();
    }

    @Override
    public CarFeatureStrategy next() {
        return this.nextStrategy;
    }
}

// ... and so on for all the strategies
CarProcessor
应该构建一个策略链,并处理每个car,直到链完成(当前策略的
next
方法返回null),或者当前策略无法处理当前car(
canHandle
当前策略方法返回false)

公共类卡处理器{
私家车服务;
私家车控制器;
公共车辆(对象页面名){
//例如,责任链在此初始化,
//但是它应该在初始化完成的地方初始化
//只调用一次而不是每次调用processCars方法
//以相反的顺序初始化责任链
CarFeatureStrategy salesCategoryStrategy=新salesCategoryStrategy(空);
CarFeatureStrategy transmissionStrategy=新的传输策略(销售类别策略);
CarFeatureStrategy bodystyleStrategy=新的bodystyleStrategy(变速箱策略);
CarFeatureStrategy fueltypeStrategy=新的fueltypeStrategy(bodystyleStrategy);
CarFeatureStrategy engineStrategy=新的engineStrategy(fueltypeStrategy);
//以此类推,直到链中的第一个战略
CarFeatureStrategy modelStrategy=新modelStrategy(…);
Car carToMatch=restController.data();
List cars=carService.findCarByConfigtype(pageName);
List dataFound=new ArrayList();
用于(汽车纸箱工艺:汽车){
CarFeatureStrategy currentStrategy=模型策略;
做{
if(!currentStrategy.canProcess(carToProcess,carToMatch)){
//如果当前策略无法处理当前车辆
//停止锁链
打破
}
dataFound.add(currentStrategy.process(carToProcess));
//转到链中的下一个战略
currentStrategy=currentStrategy.next();
}while(currentStrategy!=null)
}
}
}

首先要做的是将
CarList.get(i)
carrestapiccontroller.data()
的结果保存到变量中,而不是一次又一次地重复它们。(如果它们是简单的获取者,这主要是为了让阅读更容易
public class ModelStrategy implements CarFeatureStrategy {

    private CarFeatureStrategy nextStrategy;

    public ModelStrategy(CarFeatureStrategy nextStrategy) {
        this.nextStrategy = nextStrategy;
    }

    @Override
    public boolean canProcess(Car carToProcess, Car carToMatch) {
        // check only the model
        return carToProcess.getModel().equals(carToMatch.getModel));
    }

    @Override
    public Object process(Car carToProcess) {
        return carToProcess.getModel();
    }

    @Override
    public CarFeatureStrategy next() {
        return this.nextStrategy;
    }
}

public class DerivativeStrategy implements CarFeatureStrategy {

    private CarFeatureStrategy nextStrategy;

    public DerivativeStrategy(CarFeatureStrategy nextStrategy) {
        this.nextStrategy = nextStrategy;
    }

    @Override
    public boolean canProcess(Car carToProcess, Car carToMatch) {
        // check only the derivative property
        return carToProcess.getDerivative().equals(carToMatch.getDerivative());
    }

    @Override
    public Object process(Car carToProcess) {
        return carToProcess.getDerivative();
    }

    @Override
    public CarFeatureStrategy next() {
        return this.nextStrategy;
    }
}

// ... and so on for all the strategies
public class CarProcessor {

    private CarService carService;
    private CarRestApiController restController;

    public void processCars(Object pageName) {
        // for example purpose the chain of responsibilities is initialized here,
        // but it should be initialized somwhere where the initialization is done
        // only once rather than each time the processCars method is called

        // initialise the chain of responsibilities in revers order
        CarFeatureStrategy salesCategoryStrategy = new SalescategoryStrategy(null);
        CarFeatureStrategy transmissionStrategy = new TransmissionStrategy(salesCategoryStrategy);
        CarFeatureStrategy bodystyleStrategy = new BodystyleStrategy(transmissionStrategy);
        CarFeatureStrategy fueltypeStrategy = new FueltypeStrategy(bodystyleStrategy);
        CarFeatureStrategy engineStrategy = new EngineStrategy(fueltypeStrategy);
        // .... and so on until the first strategy in the chain
        CarFeatureStrategy modelStrategy = new ModelStrategy(...);

        Car carToMatch = restController.data();
        List<Car> cars = carService.findCarByConfigtype(pageName);
        List<Object> dataFound = new ArrayList<>();

        for (Car carToProcess : cars) {
            CarFeatureStrategy currentStrategy = modelStrategy;
            do {
                if ( !currentStrategy.canProcess(carToProcess, carToMatch)) {
                    // if current strategy cannot process the current car
                    // stop the chain
                    break;
                }

                dataFound.add(currentStrategy.process(carToProcess));
                // move to the next strategy in the chain
                currentStrategy = currentStrategy.next();

            } while (currentStrategy != null)
        }
    }
}