索引服务设计 - 同步/异步

时间:2013-04-25 18:01:38

标签: java interface indexing

我要求索引项目。此服务应运行Sync或Async。

我开始设计界面

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);
}

所以现在实现将知道如何在该标志上运行。

我知道第一个设计更好,但我需要利弊解释原因。

2 个答案:

答案 0 :(得分:1)

我说两个。

假设您计划使用第二种方法。您的实施可能如下:

public SyncOrAsyncIndex implements IndexService {
public void index(int mode) {
    if(mode == 0) {
        //sync processing code
    } else if (mode == 1) {
        //async procesisng code
    }

}

那就是说,你打算在这个索引方法或SyncOrAsyncIndex类中编写所有实现。这可能最终无法管理。 因此,索引方法最终可能会这样:

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。

答案 1 :(得分:1)

我选择第一种方法,因为

1-代码更清晰AsyncInex类只有与异步调用相关的代码,syncIndex会有自己的代码。 2-如果

,你可以避免别的
...
public void runService(IndexService service) {
     service.index()
}

// some where in your code
runService(new AsyncIndex());
// or
runService(new SyncIndex());

当您使用接口“IndexService”时,您始终可以在不更改客户端代码的情况下更改实现。 特别是如果你正在使用DI框架,你可以得到它;)。

这对于不允许客户端代码了解实现非常重要。假设您正在索引的情况,例如数据库。 您希望在数据较大时执行异步索引,或在数据较小时执行同步索引。 调用者应该不了解Index的调用方式。这样,您可以在不同情况下使用不同的策略,而无需更改调用者代码。如果你采取第二种方法,你必须做一些额外的工作。

相关问题