我想我理解你想要做什么,但你混淆了术语。如果您的目标是创建一个支持单一类型汽车的应用程序,那么 Mark 的答案就是您想要的。但是,如果您正在寻找的工厂可以创建具有不同配置的多种类型的汽车,而您在编译/启动时不知道它们是什么,那么您需要以不同的方式处理这个想法。
在这个版本中,我们将在配置文件中定义多种“类型”的汽车,因此我们将拥有一个 POJO 汽车类。
public class Car {
private String model;
private String type;
public Car() {
}
public Car(String model, String type) {
this.model = model;
this.type = type;
}
}
然后我们将拥有您的 CarFactory,只是因为我们有多个工厂配置,我们会在地图中处理它们。
public class CarFactory {
Map<String, ConfiguredCarFactory> factories = new HashMap<>();
public Car makeCar(String profile) {
return getFactory(profile).makeCar();
}
private ConfiguredCarFactory getFactory(String profile) {
ConfiguredCarFactory carFactory = factories.get(profile);
if(carFactory == null) {
carFactory = new ConfiguredCarFactory(profile);
factories.put(profile, carFactory);
}
return carFactory;
}
}
在这种情况下,为了简单起见,我使用的配置文件是属性文件的实际文件位置。这不是设置为 Bean,但如果您想创建一个 Bean 来处理地图的幕后功能,它可以非常快。
然后,最后,我们将通过配置文件配置 CarFactory 来执行实际的汽车创建。
public class ConfiguredCarFactory {
private final String profile;
private String model;
private String type;
public ConfiguredCarFactory(String profile) {
this.profile = profile;
Properties prop = new Properties();
File file = new File(profile);
try(FileInputStream input = new FileInputStream(profile)) {
prop.load(input);
model = (String) prop.get("model");
type = (String) prop.get("type");
} catch (Exception e) {
e.printStackTrace();
model = "Generic";
type = "Generic";
}
}
public Car makeCar() {
return new Car(model, type);
}
}
虽然这肯定符合您的要求,但我有点犹豫说这就是您要找的东西。提供未知数量的汽车配置作为属性并不理想,例如,将所有汽车配置存储在数据库中并通过 JPA 实例化为实体。这更加“动态”,并且更接近 Spring 的设计理念,而不是相对僵化并且需要机器上存在配置文件以及文件源的一些未知输入。