我正在尝试找到一种实现依赖于第三方库类的服务的好方法.如果库不可用或无法提供答案,我还有一个'默认'实现用作后备.
public interface Service {
public Object compute1();
public Object compute2();
}
public class DefaultService implements Service {
@Override
public Object compute1() {
// ...
}
@Override
public Object compute2() {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
该服务的实际实现将是这样的:
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();
}
} …Run Code Online (Sandbox Code Playgroud) java fallback design-patterns strategy-pattern proxy-pattern