次のようなものを使用できます。
interface Employee{
public String getName();
int getBatchId();
}
interface Filter{
boolean matches(Employee e);
}
public Filter byName(final String name){
return new Filter(){
public boolean matches(Employee e) {
return e.getName().equals(name);
}
};
}
public Filter byBatchId(final int id){
return new Filter(){
public boolean matches(Employee e) {
return e.getBatchId() == id;
}
};
}
public Employee findEmployee(Filter sel){
List<Employee> allEmployees = null;
for (Employee e:allEmployees)
if (sel.matches(e))
return e;
return null;
}
public void usage(){
findEmployee(byName("Gustav"));
findEmployee(byBatchId(5));
}
SQL クエリによるフィルタリングを行う場合は、Filter
インターフェイスを使用して WHERE 句を作成します。
このアプローチの良い点は、2 つのフィルターを次のように簡単に組み合わせることができることです。
public Filter and(final Filter f1,final Filter f2){
return new Filter(){
public boolean matches(Employee e) {
return f1.matches(e) && f2.matches(e);
}
};
}
そのように使用します:
findEmployee(and(byName("Gustav"),byBatchId(5)));
Criteria
得られるものは、Hibernateの API に似ています。