2

我有一个布尔方法

public boolean addCar(CarReg carReg, Car car){
    return ?;
}

上面的这个方法是为了传递给另一个进行实际检查的类

public class Car{ 
    Map<CarReg, Car> carMap = new HashMap<carReg, Car>();
    //if the check is successfull, the details are added to the collection
    public boolean addCar(CarReg carReg, Car car){
        If (garage.getOwner().toString == "pete"){
            carMap.put(carReg, car);
            return true;
        }
    }
}

我可以通过说 car.addCar(carReg, car); 来调用它吗?实际上,我已经尝试过,但它似乎不起作用。除非错误在其他地方。

4

1 回答 1

1

与函数式语言不同,在 Java 等面向对象的语言中,您不会传递函数,而是传递可以调用方法的对象。有几种方法可以让您的布尔方法对 Car 类可见。我将调用该方法canAddCar只是为了避免与Car#addCar.

最简单的是如果您可以在 Car 类本身中定义方法:

public class Car {
  public boolean canAddCar(CarReg carReg, Car car) {
    // logic for checking if you can add the car
  }
  public boolean addCar(CarReg carReg, Car car) { 
    if (canAddCar(carReg, car)) {
      // logic for adding the car goes here
      return true;
    } else {
      // anything special if you can't add the car?
      return false;
    }
  }
}

下一个最简单的方法是,如果您可以在传入的对象的类中定义方法,例如CarReg

这是有道理的,如果 carReg 负责检查您是否可以添加汽车。根据命名,我想你可能希望 carReg 也负责添加汽车,但我没有在这里展示:

public class CarReg {
  public boolean canAddCar(Car car) {
    // logic for testing if you can add the car, for example:
    return (car.getOwner().toString().equals("pete"));
  }
}

public class Car {
  public boolean addCar(CarReg carReg, Car car) {
    if (carReg.canAddCar(car)) {
      // ...
    } else {
      // ...
    }
  }
}

接下来,您可以将另一个对象传递给可以负责检查的类。这可以是方法的另一个对象,也可以是类addCar的属性Car。我在这个例子中展示了后者(因为前面的例子基本上是前者):

// might as well use an interface if you'll have multiple methods of checking
public interface CarChecker {
  boolean canAddCar(CarReg carReg, Car car);
}

// specific implementation of the CarChecker interface
// you can instantiate this and pass it into the Car class via a setter
public class MyCarChecker implements CarChecker {
  public boolean canAddCar(CarReg carReg, Car car) {
    // checking logic goes here
  }
}

public class Car {
  private CarChecker carChecker;
  // you'll have to implent getCarChecker and setCarChecker 
  // (or let your IDE generate the getters and setters)

  // assuming you'll call setCarChecker somewhere (or have it wired up via IoC)

  public boolean addCar(CarReg carReg, Car car) {
    if (carChecker.canAddCar(carReg, car)) {
      // ...
    } else {
      // ...
    }
  }
}

还有其他几种方法(匿名类、单例类、静态方法),但这些是最常见的,应该可以帮助您入门。

于 2012-07-07T16:02:05.447 回答