我有一個如下定義的語言翻譯界面。春天:移動stradegy代碼或保留在XML文件?
public interface TranslationService {
public TranslationResult translate(TranslationRequeset req);
public int maxTranslatableCount();
}
並通過如下使用谷歌,必應...等有接口的幾種實現方式:
public class BingTranslationServiceImpl implements TranslationService {
public TranslationResult translate(TranslationRequeset req){}
public int maxTranslatableCount(){return 10000;}
}
public class GoogleTranslationServiceImpl implements TranslationService {
public TranslationResult translate(TranslationRequeset req){}
public int maxTranslatableCount(){return 2000;}
}
public class FooTranslationServiceImpl implements TranslationService {
public TranslationResult translate(TranslationRequeset req){}
public int maxTranslatableCount(){return 50000;}
}
然後在我們的客戶端代碼,我們必須執行,如果一個特定的故障轉移翻譯服務失敗。
爲了實現這一目標,我介紹了一個「TranslationProxy」在列表定義故障切換策略如下:
基本上這個迭代通過列表,如果一個特定的服務未能轉化。
public class TranslationProxy implements TranslationService {
private List<TranslationService> services;
TranslationResult translate(TranslationRequeset req) {
//
}
public List<TranslationBusinessLogic> getServices() {
return services;
}
public void setServices(List<TranslationBusinessLogic> services) {
this.services = services;
}
}
然後在我的Spring配置我定義的服務實現如下:
<bean id="bing" class="com.mycompany.prj.BingTranslationServiceImpl" scope="singleton"/>
<bean id="google" class="com.mycompany.prj.GoogleTranslationServiceImpl" scope="singleton"/>
<bean id="foo" class="com.mycompany.prj.FooTranslationServiceImpl" scope="singleton"/>
併爲每個故障切換策略,我定義 「TranslationProxy」 豆如下:
<bean id="translationProxy_Bing_Google" class="com.mycompany.prj.TranslationProxy" scope="singleton">
<property name="services">
<list>
<ref bean="bing"/>
<ref bean="google"/>
</list>
</property>
</bean>
<bean id="translationProxy_Foo_Bing_Google" class="com.mycompany.prj.TranslationProxy" scope="singleton">
<property name="services">
<list>
<ref bean="foo"/>
<ref bean="bing"/>
<ref bean="google"/>
</list>
</property>
</bean>
在客戶端代碼:
class SomeBusinessLogic {
@Autowired
@Qualified("translationProxy_Bing_Google")
private TranslationService translationService;
public void some_method_which_uses_translation() {
result = translationService(request);
}
}
另一個地方:
class SomeAnotherBusinessLogic {
@Autowired
@Qualified("translationProxy_Foo_Bing_Google")
private TranslationService translationService;
public void some_method_which_uses_translation_with_different_failover_stradegy() {
result = translationService(request);
}
}
這不是實現這個故障切換stradegy最乾淨的方式是什麼?
我被要求將故障轉移條件轉移到客戶端代碼中。
喜歡的東西以下(在彈簧是不可能的):
class SomeBusinessLogic {
@Autowired
@SomeAnnotationDefiningTheStradegy("bing","google")
private TranslationService translationService;
public void some_method_which_uses_translation() {
result = translationService(request);
}
這裏的「SomeAnnotationDefiningTheStradegy」是一個註釋這將填補與所述參數定義的豆的列表。
+1另一個不錯的選擇。再一次,以上所有內容在執行過程中幾乎完全相同。這取決於OP如何構建它。 – MattSenter
添加第四個簡單翻譯服務時,爲不同(簡單)翻譯服務創建枚舉會導致代碼更改。問題在於爲故障轉移策略更改代碼,而不是單個翻譯服務。 –