从租车系统看OOP设计:如何用Java实现客车、货车和皮卡车的类继承关系
租车系统的业务场景看似简单,却蕴含着面向对象设计的精髓。当我们需要处理客车、货车和皮卡车这三种不同类型的车辆时,如何设计类结构才能既满足当前需求,又保持足够的扩展性?这不仅是初学者面临的挑战,也是资深开发者不断思考的设计哲学。
1. 理解业务需求与领域模型
在开始编码之前,我们需要深入理解租车系统的核心业务需求:
- 车辆类型:系统需要管理三种主要车型——客车、货车和皮卡车
- 核心属性:所有车辆都有名称和租金这两个基本属性
- 差异化能力:
- 客车:只能载人,需要记录最大载客量
- 货车:只能载货,需要记录最大载重量
- 皮卡车:客货两用,需要同时记录载客量和载重量
这个业务模型看似简单,但已经包含了继承和多态的应用场景。我们需要设计一个类结构,既能表达共性,又能处理差异。
2. 基础类结构设计
2.1 基类Vehicle的设计
所有车辆的共性可以抽象到一个基类中:
public abstract class Vehicle {
protected String name;
protected int dailyRent;
public Vehicle(String name, int dailyRent) {
this.name = name;
this.dailyRent = dailyRent;
}
public abstract double calculateRent(int days);
public String getName() {
return name;
}
public int getDailyRent() {
return dailyRent;
}
}
这个基类定义了所有车辆共有的属性和行为:
name:车辆名称dailyRent:每日租金calculateRent:计算租金的抽象方法(多态的体现)
2.2 派生类的实现
基于这个基类,我们可以创建具体的车辆类型:
客车类:
public class PassengerVehicle extends Vehicle {
private int maxPassengers;
public PassengerVehicle(String name, int dailyRent, int maxPassengers) {
super(name, dailyRent);
this.maxPassengers = maxPassengers;
}
@Override
public double calculateRent(int days) {
return days * dailyRent;
}
public int getMaxPassengers() {
return maxPassengers;
}
}
货车类:
public class CargoVehicle extends Vehicle {
private double maxCargoWeight;
public CargoVehicle(String name, int dailyRent, double maxCargoWeight) {
super(name, dailyRent);
this.maxCargoWeight = maxCargoWeight;
}
@Override
public double calculateRent(int days) {
return days * dailyRent;
}
public double getMaxCargoWeight() {
return maxCargoWeight;
}
}
皮卡类:
public class PickupTruck extends Vehicle {
private int maxPassengers;
private double maxCargoWeight;
public PickupTruck(String name, int dailyRent, int maxPassengers, double maxCargoWeight) {
super(name, dailyRent);
this.maxPassengers = maxPassengers;
this.maxCargoWeight = maxCargoWeight;
}
@Override
public double calculateRent(int days) {
return days * dailyRent;
}
public int getMaxPassengers() {
return maxPassengers;
}
public double getMaxCargoWeight() {
return maxCargoWeight;
}
}
3. 多态与接口的应用
为了更灵活地处理不同类型车辆的能力,我们可以引入接口:
public interface PassengerCapacity {
int getMaxPassengers();
}
public interface CargoCapacity {
double getMaxCargoWeight();
}
然后修改我们的类实现:
public class PassengerVehicle extends Vehicle implements PassengerCapacity {
// 实现不变
}
public class CargoVehicle extends Vehicle implements CargoCapacity {
// 实现不变
}
public class PickupTruck extends Vehicle implements PassengerCapacity, CargoCapacity {
// 实现不变
}
这种设计的好处是:
- 更清晰地表达了每种车辆的能力
- 可以在不修改类层次结构的情况下添加新的能力
- 使类型检查更加明确
4. 系统实现与业务逻辑
有了良好的类设计,系统实现就变得清晰明了:
public class RentalSystem {
private List<Vehicle> vehicles;
public RentalSystem() {
vehicles = new ArrayList<>();
initializeVehicles();
}
private void initializeVehicles() {
// 添加各种车辆
vehicles.add(new PassengerVehicle("小型客车", 800, 5));
vehicles.add(new PassengerVehicle("大型客车", 1500, 55));
vehicles.add(new CargoVehicle("小型货车", 500, 0.45));
vehicles.add(new CargoVehicle("大型货车", 2000, 35));
vehicles.add(new PickupTruck("皮卡车", 450, 5, 2.0));
}
public RentalResult calculateRental(List<RentalItem> items) {
int totalPassengers = 0;
double totalCargo = 0.0;
int totalCost = 0;
for (RentalItem item : items) {
Vehicle vehicle = vehicles.get(item.getVehicleIndex());
int days = item.getDays();
totalCost += vehicle.calculateRent(days);
if (vehicle instanceof PassengerCapacity) {
totalPassengers += ((PassengerCapacity)vehicle).getMaxPassengers() * days;
}
if (vehicle instanceof CargoCapacity) {
totalCargo += ((CargoCapacity)vehicle).getMaxCargoWeight() * days;
}
}
return new RentalResult(totalPassengers, totalCargo, totalCost);
}
}
这里的关键点:
- 使用
instanceof检查车辆能力 - 通过接口方法获取具体能力值
- 计算结果封装在
RentalResult值对象中
5. 设计模式的应用与优化
5.1 工厂模式创建车辆
为了更好管理车辆创建,可以引入工厂模式:
public class VehicleFactory {
public static Vehicle createVehicle(VehicleType type, String name, int dailyRent,
Integer maxPassengers, Double maxCargoWeight) {
switch (type) {
case PASSENGER:
return new PassengerVehicle(name, dailyRent, maxPassengers);
case CARGO:
return new CargoVehicle(name, dailyRent, maxCargoWeight);
case PICKUP:
return new PickupTruck(name, dailyRent, maxPassengers, maxCargoWeight);
default:
throw new IllegalArgumentException("Unknown vehicle type");
}
}
}
5.2 策略模式计算租金
对于可能变化的租金计算逻辑,可以使用策略模式:
public interface RentalPricingStrategy {
double calculateRent(Vehicle vehicle, int days);
}
public class StandardPricingStrategy implements RentalPricingStrategy {
@Override
public double calculateRent(Vehicle vehicle, int days) {
return vehicle.getDailyRent() * days;
}
}
// 在Vehicle类中
private RentalPricingStrategy pricingStrategy = new StandardPricingStrategy();
public double calculateRent(int days) {
return pricingStrategy.calculateRent(this, days);
}
6. 测试与验证
良好的设计需要通过测试来验证:
public class RentalSystemTest {
private RentalSystem system;
@Before
public void setUp() {
system = new RentalSystem();
}
@Test
public void testPassengerVehicleRental() {
List<RentalItem> items = List.of(new RentalItem(0, 2)); // 租用小型客车2天
RentalResult result = system.calculateRental(items);
assertEquals(10, result.getTotalPassengers()); // 5人*2天
assertEquals(0.0, result.getTotalCargo(), 0.01);
assertEquals(1600, result.getTotalCost()); // 800*2
}
@Test
public void testMixedRental() {
List<RentalItem> items = List.of(
new RentalItem(0, 1), // 小型客车1天
new RentalItem(4, 3) // 皮卡车3天
);
RentalResult result = system.calculateRental(items);
assertEquals(20, result.getTotalPassengers()); // 5*1 + 5*3
assertEquals(6.0, result.getTotalCargo(), 0.01); // 2.0*3
assertEquals(2150, result.getTotalCost()); // 800*1 + 450*3
}
}
7. 扩展性与维护性考虑
7.1 添加新车型
当需要添加新的车型时,比如露营车(可载人载货且有住宿功能),我们的设计可以轻松扩展:
public class CamperVan extends Vehicle implements PassengerCapacity, CargoCapacity {
private int maxPassengers;
private double maxCargoWeight;
private boolean hasToilet;
// 构造器和方法实现
}
7.2 动态定价策略
通过组合策略模式,可以实现动态定价:
public class DiscountPricingStrategy implements RentalPricingStrategy {
private double discountRate;
public DiscountPricingStrategy(double discountRate) {
this.discountRate = discountRate;
}
@Override
public double calculateRent(Vehicle vehicle, int days) {
double basePrice = vehicle.getDailyRent() * days;
return basePrice * (1 - discountRate);
}
}
// 使用示例
PassengerVehicle bus = new PassengerVehicle("豪华巴士", 2000, 30);
bus.setPricingStrategy(new DiscountPricingStrategy(0.1)); // 10%折扣
double price = bus.calculateRent(5); // 原价10000,现价9000
8. 性能与内存优化
对于频繁创建的车辆实例,可以考虑使用享元模式:
public class VehicleFlyweightFactory {
private static Map<String, Vehicle> vehicles = new HashMap<>();
public static Vehicle getVehicle(String key, Supplier<Vehicle> creator) {
return vehicles.computeIfAbsent(key, k -> creator.get());
}
}
// 使用方式
Vehicle bus = VehicleFlyweightFactory.getVehicle("bus-30",
() -> new PassengerVehicle("豪华巴士", 2000, 30));
这种设计特别适合车辆配置固定的场景,可以大幅减少内存使用。
662



被折叠的 条评论
为什么被折叠?



