我有一个从xml文件创建的工厂,可以避免长时间 - 否则,如果xml是动态的,我不想硬编码对象? Java代码 -
public static IDevice createDevice(String name, Element element) {
IDevice device;
if (name.equals("Autopilot")) {
String strSpeed = element.getAttribute("maxSpeed");
int speed = Integer.parseInt(strSpeed);
device = new AutoPilot(speed);
return device;
} else if (name.equals("Camera")) {
device = new CameraDevice();
return device;
} else if (name.equals("ClassifiedDevice")) {
device = new ClassifiedDevice();
return device;
}
return null;
}
xml文件中有“设备”具有不同的属性,工厂根据选择创建它们来创建它们。但设备列表是动态的,可以在将来扩展。
<UAV>
<Device name="Autopilot" maxSpeed = "70" minSpeed = "40" />
<Device name="Camera" maxRange = "7000" />
<Device name="ClassifiedDevice" range = "8000" time = "4" />
</UAV>
答案 0 :(得分:-1)
通常,如果你想避免长else if
,你可以(取决于你的语言,但我猜它是C#或Java),使用switch
语句。这是你正在寻找的吗?
例如在C#中(在Java中可能看起来相同,不确定):
switch(name)
{
case "Autopilot":
var strSpeed = element.getAttribute("maxSpeed");
var speed = int.parse(strSpeed);
return new AutoPilot(speed);
return device;
//other cases ...
default:
// unknown device?
// return some default value or thrown exception or whatever you want :D
}
您也可以尝试一种功能性方法,可能是这样的: (注意:这是C#,我不知道这是否适用于Java,但据我所知应该有一个等价物)
var factories = new Dictionary<string, Func<IDevice>>
{
{ "Autopilot", ()=>{
string strSpeed = element.getAttribute("maxSpeed");
var speed = int.parse(strSpeed);
return new AutoPilot(speed);
}
},
// more "cases"
//{ "", ... }
};
//simply call by:
IDevice device = factories[name](); // maybe check if the name is in the dictionary first...