如何在 Single 方法中为不同的端点创建对象,而不是 java 中的 if 循环

if (type.equalsIgnoreCase("Android")) {

    return new AndroidApi;

} else if (type.equalsIgnoreCase("iOS")) {

    return new  IosAPi;

} else if (type.equalsIgnoreCase("Windows")) {

    return new WindowsApi;

}

我如何创建对象而不是 if 条件那里有 20 个端点。


浮云间
浏览 108回答 3
3回答

呼如林

您可以将 API 实现的类型和供应商放在地图中,例如:public static final Map<String, Supplier<Api>> supplierMap = Map.of(&nbsp; &nbsp; &nbsp; &nbsp; "android",&nbsp; AndroidApi::new,&nbsp; &nbsp; &nbsp; &nbsp; "ios",&nbsp; &nbsp; &nbsp; IosApi::new,&nbsp; &nbsp; &nbsp; &nbsp; "windows",&nbsp; WindowsApi::new);public static Api getApi(String type) {&nbsp; &nbsp; return supplierMap.get(type.toLowerCase()).get();}假设它们都实现了一个接口。您可以这样调用上述方法:Api api = getApi("Android");

偶然的你

您可以使用工厂设计模式。interface OperatingSystem{&nbsp; &nbsp; void runProcess();}class AndroidApi implements OperatingSystem {&nbsp; &nbsp; public void runProcess() {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated method stub&nbsp; &nbsp; }}class IosAPi implements OperatingSystem {&nbsp; &nbsp; public void runProcess() {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated method stub&nbsp; &nbsp; }}class WindowsApi implements OperatingSystem {&nbsp; &nbsp; public void runProcess() {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated method stub&nbsp; &nbsp; }}class OSFactory{&nbsp; &nbsp; static OperatingSystem getOPApi(String type){&nbsp; &nbsp; &nbsp; &nbsp; if (type.equalsIgnoreCase("Android")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new AndroidApi();&nbsp; &nbsp; &nbsp; &nbsp; } else if (type.equalsIgnoreCase("iOS")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new&nbsp; IosAPi();&nbsp; &nbsp; &nbsp; &nbsp; } else if (type.equalsIgnoreCase("Windows")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new WindowsApi();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}public class Client{&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; OperatingSystem os=OSFactory.getOPApi("Android");&nbsp; &nbsp; }}

千万里不及你

是的,您可以使用工厂设计模式或使用 Java 反射 API 来实现。使用 Java 反射 API,我们可以执行如下操作,为这里提到的所有 Api 类创建一个基类。将基类视为public abstract class BaseApi.HashMap<String,String> map = new HashMap<String,String>();map.put("Android","AndroidApi");map.put("iOS","IosApi");map.put("Windows","WindowsApi");public static BaseApi getInstance(String type){&nbsp; &nbsp; BaseApi obj = (BaseApi)Class.forName(type).newInstance();&nbsp; &nbsp; return obj;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java