2013-04-25 95 views
1

我有索引项目的要求。此服务应运行同步或异步。索引服务设计 - 同步/异步

我开始设计一个接口

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的设计,它有一个作为异步服务或as执行的标志一个同步服务:

public interface IndexService{ 
    public void index(int mode); 
} 

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

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

回答

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框架,你可以踢它;)。

这对于不允许客户端代码了解实现如此重要。假设你在索引数据库的情况下。 您希望在数据很大时执行异步索引,或者在数据很小时执行同步索引。 调用者应该不知道调用索引的方式。这样你可以在不改变呼叫者代码的情况下在不同的情况下有不同的策略。如果你采取第二种方法,你必须做一些额外的工作。

1

我说都有。

假设您打算使用第二种方法。你implmentation可能看起来像:

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。