切换多种服务替代方案

问题描述 投票:0回答:1

我有一个交换机调用多个服务,如:

switch (condition) {
case 1:
    return service1.methodA(args....);
case 2:
    return service2.methodX(args....);
case 3:
    return service3.methodZ(args....);
.
.
.
default:
    break;
}

实现这个的最好方法是什么?

服务是@Autowired并返回相同的对象。

java service switch-statement
1个回答
-1
投票

您可以使它们都实现一个通用接口:

interface YourCommonServiceName {
    YourReturnObject yourMethodName(/* your arguments */);
}

然后,您最初可以将所有服务添加到地图,具体取决于他们的条件:

private final Map<Integer, YourCommonServiceName> services;

@Autowired
public YourClass(YourCommonServiceName serviceA, YourCommonServiceName serviceB, /* ... */) {
    Map<Integer, YourCommonServiceName> map = new HashMap<>();

    map.put(1, serviceA);
    map.put(2, serviceB);
    // ...

    services = Collections.unmodifiableMap(map);
}

然后你可以用条件作为参数调用services-map:

YourCommonServiceName service = services.get(condition);
if(service == null) {
    // do something if nothing matches
    return;
}

然后使用参数调用方法:

YourReturnObject o = service.yourMethodName(args...);

您也可以直接在@Configuration类中创建该地图:

@Bean
public Map<Integer, YourCommonServiceName> services(YourCommonServiceName serviceA, YourCommonServiceName serviceB, ...) {
    Map<Integer, YourCommonServiceName> map = new HashMap<>();

    map.put(1, serviceA);
    map.put(2, serviceB);
    // ...

    return Collections.unmodifiableMap(map);
}

然后将Map注入其他类:

public YourClass(Map<Integer, YourCommonServiceName> services) {
    this.services = services;
}
© www.soinside.com 2019 - 2024. All rights reserved.