Java 11 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Create interfaces that describe the API:
public interface SpeedModel {
double getSpeedMph(double timeSec, int weightPounds,
int horsePower);
}
public interface Vehicle {
void setSpeedModel(SpeedModel speedModel);
double getSpeedMph(double timeSec);
}
public interface Car extends Vehicle {
int getPassengersCount();
}
public interface Truck extends Vehicle {
int getPayloadPounds();
}

  1. Use factories, which are classes that generate objects that implement certain interfaces. A factory hides from the client code the details of the implementation, so the client deals with an interface only. It is especially helpful when an instance creation requires a complex process and/or significant code duplication. In our case, it makes sense to have a FactoryVehicle class that creates objects of classes that implement the Vehicle, Car, or Truck interface. We will also create the FactorySpeedModel class, which generates objects of a class that implements the SpeedModel interface. Such an API allows us to write the following code:
public static void main(String... arg) {
double timeSec = 10.0;
int horsePower = 246;
int vehicleWeight = 4000;
Properties drivingConditions = new Properties();
drivingConditions.put("roadCondition", "Wet");
drivingConditions.put("tireCondition", "New");
SpeedModel speedModel = FactorySpeedModel.
generateSpeedModel(drivingConditions);
Car car = FactoryVehicle.
buildCar(4, vehicleWeight, horsePower);
car.setSpeedModel(speedModel);
System.out.println("Car speed (" + timeSec + " sec) = "
+ car.getSpeedMph(timeSec) + " mph");
}
  1. Observe that the code behavior is the same as in the previous examples:

However, the design is much more extensible.