就像 Jon Skeet 在他的评论中所说的那样,如果它不是 aMountainBike
并且只是一个 plain ,你就不能施放它Bicycle
。您可以做的是创建一个构造函数,MountainBike
该构造函数将Bicycle
其作为参数:
public MountainBike(Bicycle bicycle) {
// Copy bicycle's properties
}
而是调用它:
MountainBike mb = new MountainBike(Bicycle bicycle);
如果MountainBike
由于某种原因无法修改类,还可以创建static
工厂方法:
public class MountainBikeFactory {
public static MountainBike createMountainBike(Bicycle bicycle) {
MountainBike mb = new MountainBike();
// Copy bicycle's properties
return mb;
}
}
并称之为:
MountainBike mb = MountainBikeFactory.create(bicycle);
编辑:查看您发布的作为对该问题的评论的信息后,您似乎可以尝试构建器模式。构建器将包含所有属性作为变量(是的,它将很长,有 100 多个变量),当您从文件中发现属性时,将它们设置在构建器上。然后,最后,当您调用构建器的build()
方法时,让它解析要创建的自行车类型,并使用多态性来处理您创建的自行车的属性组。
例如:
public class BikeBuilder {
private String model;
private String wheelSize;
private String shocks;
private String racingHandleBarType;
// returns "this" so you can chain calls, common in builders, not necessary
public BikeBuilder setModel(String model) {
this.model = model;
return this;
}
// Other setters
public Bike build() {
Bike bike;
// Determine which kind of bike it is and create it
if (shocks != null) {
bike = new MountainBike();
handleMountainBike((MountainBike) bike);
} else if (racingHandleBarType != null) {
bike = new RacingBike();
handleRacingBike((RacingBike) bike);
} else {
bike = new Bike();
}
handleCommonAttributes(bike);
return bike;
}
// All bikes have these attributes
private void handleCommonAttributes(Bike bike) {
bike.setModel(model);
bike.setWheelSize(wheelSize);
}
private void handleMountainBike(MountainBike bike) {
bike.setShocks(shocks);
}
private void handleRacingBike(RacingBike bike) {
bike.setRacingHandleBarType(racingHandleBarType);
}
}
这使您可以即时构建自行车并在读取文件结束时而不是开始时决定其类型。它充当一种容器。如果您有多种扩展类型,Bike
您可以为它们创建新方法。这至少会让你开始。