我正在使用Android应用程序来访问网络上的硬件。每个硬件制造商的函数调用都是相同的,但响应的响应和解析将因制造商而异。我最初的想法是:
public class ManufacturerONEobject {
public void getURL(){ manufacturer Specific Code }
public void postURL(){ manufacturer Specific Code }
}
public class ManufacturerTWOobject {
public void getURL(){ manufacturer Specific Code }
public void postURL(){ manufacturer Specific Code }
}
public class GenericObject(){
ManufacturerONEobject manufacturerONE = null;
ManufacturerTWOobject manufacturerTWO = null;
if(manufacturer.equals("manufacturerONE"){
manufacturerONE = new ManufacturerONEobject();
}
if(manufacturer.equals("manufacturerTWO"){
manufacturerTWO = new ManufacturerTWOobject();
}
public void getURL(){ specificManufacturerObject.getURL();}
public void postURL(){ specificManufacturerObject.postURL();}
}
我选择了这种安排,因为它允许我添加新的制造商到我的应用程序,只需在我的通用对象中添加一个全局变量和if语句,并且所有制造商特定代码将在其自己的类中。但是,我很快就会有30个全局变量,其中只有一个实际被使用。我查看了Generic Classes,但是我没有看到将我的泛型类的方法链接到将在运行时确定的制造商特定类的方法。是否有更优雅和/或更有效的方法来做到这一点?