假设我有以下 DAO 接口(interface):
public interface CountryData {
/**
* Get All Countries.
*
* @return A Collection of Countries.
* @throws DataAccessException Thrown if there is an error communicating with the data store. The Exception's
* Cause Exception can usually be examined to determine the exact nature of the
* error.
* @since 1.0.0
*/
public List<Country> getAll();
}
进一步假设我正在抽象这个 DAO,因为我可能会提供 2 个实现,一个用于数据库,一个用于 Web 服务。
我想重载 getAll 方法以接受某种排序参数来指示返回值的排序方式。
不过,我不想将接口(interface)绑定(bind)到特定的实现。例如,数据库实现将使用 ORDER BY 子句,并且需要数据库列列表和顺序方向,例如“ASC”或“DESC”,而 Web 服务实现则不需要。
在不将调用者耦合到特定实现的情况下提供此类参数的最佳做法是什么?
编辑
对我的问题的小澄清。我不仅要指定一个参数来指示订单方向,还要指定什么。
例如,假设我的 Country 模型定义如下:
public final class Country implements Serializable {
private int id;
private String name;
public Country() {
}
public Country(Country countryToCopy) {
this.id = countryToCopy.getId();
this.name = countryToCopy.getName();
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
我希望返回值按name 升序排列。我可以按照建议使用 ENUM 作为订单方向,但是在不公开实现细节的情况下指定要订购的属性的最佳实践是什么?
最佳答案
要么是 boolean 值:
public List<Country> getAll(boolean ascending);
或者一个枚举:
enum SortOrder {
ASCENDING,
DESCENDING,
RANDOM,
NONE
}
public List<Country> getAll(SortOrder order);
实际上实现这不是界面的工作。只需确保接口(interface)接受的任何输入都可以由您的任何一个类处理。
关于java - 指定对 DAO 方法的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8033041/