gpt4 book ai didi

Java 回退模式

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:13 25 4
gpt4 key购买 nike

我正在尝试找到一种很好的方法来实现依赖于第三方库类的服务。我还有一个“默认”实现,可在库不可用或无法提供答案时用作回退。

public interface Service {

public Object compute1();

public Object compute2();
}

public class DefaultService implements Service {

@Override
public Object compute1() {
// ...
}

@Override
public Object compute2() {
// ...
}
}

服务的实际实现类似于:

public class ServiceImpl implements Service {
Service defaultService = new DefaultService();
ThirdPartyService thirdPartyService = new ThirdPartyService();

@Override
public Object compute1() {
try {
Object obj = thirdPartyService.customCompute1();
return obj != null ? obj : defaultService.compute1();
}
catch (Exception e) {
return defaultService.compute1();
}
}

@Override
public Object compute2() {
try {
Object obj = thirdPartyService.customCompute2();
return obj != null ? obj : defaultService.compute2();
}
catch (Exception e) {
return defaultService.compute2();
}
}
}

当前的实现似乎有点重复,只是对服务的实际调用不同,但 try/catch 和默认机制几乎相同。此外,如果在服务中添加另一种方法,实现看起来几乎是一样的。

是否有可能适用于此的设计模式(proxystrategy)使代码看起来更好并减少进一步添加的复制粘贴?

最佳答案

代理可能会在这方面为您提供帮助。下面的示例未经测试,但应该让您了解可以放置什么:

public class FallbackService implements InvocationHandler {

private final Service primaryService;
private final Service fallbackService;

private FallbackService(Service primaryService, Service fallbackService) {
this.primaryService = primaryService;
this.fallbackService = fallbackService;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Object result = method.invoke(primaryService, args);
if (result != null) return result;
} catch (Exception ignore) {}
return method.invoke(fallbackService, args);
}

public static Service createFallbackService(Service primaryService, Service fallbackService) {
return (Service) Proxy.newProxyInstance(
Service.class.getClassLoader(),
new Class[] { Service.class },
new FallbackService(primaryService, fallbackService)
);
}
}

关于Java 回退模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com