不确定标题是否公正。我是 Java 的新手,正在尝试弄清楚如何让一个类使用不同的“服务”。假设我有一个 APIRequest 类,这个类需要能够根据需要使用不同的 API。例子。我需要运送一个包裹,如果包裹低于 32OZ 我需要使用 Endicia,否则我需要使用 FedEx。我有 2 个“服务”类 FedexRequest 和 EndiciaRequest。我试图允许 APIRequest 类根据包的重量使用其中一个。我创建了一个名为 APIService 的类,它有一个名为 getService 的静态方法。它只是创建一个字符串名称的映射 ->像这样的请求类......
public class APIService {
private static Map<String, Object> services = new HashMap<>();
private static final Map<String, String> availableServices = new HashMap() {{
put("fedex", "FedexRequest");
put("endicia", "EndiciaRequest");
}};
public static Object getService(String type) {
if(services.containsKey(type)) {
return services.get(type);
}
return null;
}
static {
for(Map.Entry<String, String> serv : availableServices.entrySet()) {
try {
Class<?> cls = Class.forName(serv.getValue());
services.put(serv.getKey(), cls.newInstance());
} catch(Exception e) {
services.put(serv.getKey(), new Class[1]);
}
}
}
现在我可以调用 APIService.getService("fedex");但是我真的很难弄清楚如何在我的 APIRequest 类中使用它,因为我需要做一些类似...
this.service = (FedexRequest) APIService.getService("fedex");
//or
this.service = (EndiciaRequest) APIService.getService("endicia);
但这打破了等式的整个动态部分,如果我以后需要添加另一项服务怎么办? 我尝试让 FedexRequest 和 EndiciaRequest 都实现一个 Request 接口(interface),然后使用
this.service = (Request) APIService.getService("fedex");
但这给了我一个 Java.lang.Class 错误,说它不能转换为 Request。我假设这是因为 Request 是一个接口(interface),所以您不能在实现类上使用 cls.newInstance() 然后转换为接口(interface)。
我真的不知道如何允许我的 APIRequest 类使用 FedexRequest 或 EndiciaRequest,而不专门使用类型转换,以便它可以是动态的,我们可以在以后添加服务而无需重新编码整个事情。我来自 PHP,在那里这将非常简单,因为您不必显式定义类型。任何帮助将不胜感激。谢谢。
最佳答案
如果我是你,我会做以下事情:
这是服务接口(interface)的实现:
public interface Service {
public void performAction();
//other common functions...
}
对您的 APIService 类的一个小修改:
public class APIService {
private static Map<String, Service> services = new HashMap<>();
private static final Map<String, String> availableServices = new HashMap() {{
put("fedex", "com.finity.shipping.api.fedexapi.FedexRequest");
put("endicia", "com.finity.shipping.api.endiciaapi.EndiciaRequest");
}};
public static Service getService(String type) {
return services.get(type);
}
static {
for(Map.Entry<String, String> serv : availableServices.entrySet()) {
try {
Class<?> cls = Class.forName(serv.getValue());
services.put(serv.getKey(), cls.newInstance());
} catch(Exception e) {
services.put(serv.getKey(), new Class[1]);
}
}
}
}
每次您需要将服务添加到您的应用程序时,只需实现服务接口(interface):
public class FedexRequest implements Service {
public void performAction() {
//do something
}
}
最后在你使用 this.service
的类中:
Service service;
...
this.service = APIService.getService("fedex");
this.service.performAction();
关于java - 在java中返回和使用不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38980975/