我有一个索引项目的要求。此服务应运行同步或异步。
我开始设计一个接口
public interface IndexService{
public void index();
}和两个实现,一个用于异步索引:
public class AsyncIndex implements IndexService {
public void index(){
//... Creates a Thread and index the items
}
}另一个连接到同步索引
public class SyncIndex implements IndexService {
public void index(){
//... Creates a Thread and index the items
}
}但现在有了另一种设计,它有一个IndexService,他有一个标志来作为异步服务或同步服务执行:
public interface IndexService{
public void index(int mode);
}因此,现在实现将知道如何基于该标志运行。
我知道第一种设计更好,但我需要正反两方面的解释。
发布于 2013-04-26 17:22:29
我选择第一种方法是因为
1-代码是更干净的,AsyncInex类只有与异步调用相关的代码,而syncIndex会有自己的代码。2-如果有其他情况,你可以避免
...
public void runService(IndexService service) {
service.index()
}
// some where in your code
runService(new AsyncIndex());
// or
runService(new SyncIndex());当您使用接口"IndexService“时,您可以随时更改实现,而无需更改客户端代码。特别是如果你正在使用依赖注入框架,你可以尝试一下;)。
这对于不让客户端代码知道实现是非常重要的。假设您正在对数据库进行索引。你想在数据量大的时候做异步索引,或者在数据小的时候做同步索引。调用者不应该知道索引的调用方式。这样,您可以在不同情况下使用不同的策略,而无需更改调用者的代码。如果你采用第二种方法,你必须做一些额外的工作。
发布于 2013-04-26 10:54:34
我两个都说。
假设您计划使用第二种方法。您的实现可能如下所示:
public SyncOrAsyncIndex implements IndexService {
public void index(int mode) {
if(mode == 0) {
//sync processing code
} else if (mode == 1) {
//async procesisng code
}
}也就是说,您是否要在此索引方法或SyncOrAsyncIndex类中编写所有实现。这很可能最终会变得难以管理。因此,index方法可能会像这样结束:
public void index(int mode) {
if(mode == 0) {
new SyncIndex().index(); //for example
} else if (mode == ) {
new AsyncIndex().index(); //for example
}
}假设您决定支持第三种模式。想象一下索引方法或SyncOrAsyncIndex类的困境。因此,第一种方法是必要的。
因此,根据“代码到接口”的策略,建议使用第一种方法。如果调用者知道索引的类型,他们就可以实例化特定的类型并使用它。
另外,与第一种方法一起,第二种方法可能需要作为工厂或策略,以根据传递的参数计算使用哪种类型的索引。然后,调用者将通过SyncOrAsyncIndex使用SyncIndex或AsyncIndex。
https://stackoverflow.com/questions/16221603
复制相似问题