这是一个经典的工厂模式问题。
解决方案是每当您必须维护静态 Map 并且每当您有新的“Bar”类型时,您都需要首先在地图中注册它,因此无论何时您想要该类型的对象,您都可以简单地从地图中选择它。
考虑以下类
interface IVehicle {
public void drive();
public void stop();
}
class Car implements IVehicle {
public void drive(){
//logic goes here
}
public void stop(){
//logic goes here
}
}
class VehicleFactory{
public IVehicle createVehicle(String VehicleType){
IVehicle vehicle = null;
if("Car".equalsIgnoreCase(VehicleType) ){
vehicle = new Car();
}
if("Bus".equalsIgnoreCase(VehicleType) ){
//vehicle = new Bus();
}
if("Train".equalsIgnoreCase(VehicleType) ){
//vehicle = new Train();
}
return vehicle;
}
}
因此,每当您拥有一种新型车辆时,您都必须通过添加新车辆类型的代码来更改方法。
解决方案是改进 VehicleFactory 类,如下所示,所有车辆类型都应在地图中注册,如下所示。
class Car implements IVehicle {
static{
VehicleFactoryFlexible.registerVehicle("Car", new Car());
}
public void drive(){
//logic goes here
}
public void stop(){
//logic goes here
}
public IVehicle createVehicle(){
return (IVehicle) new Car();
}
}
public class VehicleFactoryFlexible {
static Map vehicleRegistry = new HashMap();
public static void registerVehicle(String vehicleType, IVehicle veh){
vehicleRegistry.put(vehicleType, veh);
}
public IVehicle createVehicle(String vehicleType){
IVehicle vehicle = (IVehicle)vehicleRegistry.get(vehicleType);
return vehicle.createVehicle();
}
}