与函数式语言不同,在 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 {
// ...
}
}
}
还有其他几种方法(匿名类、单例类、静态方法),但这些是最常见的,应该可以帮助您入门。