我只使用自定义对象的可排序集合,然后根据谓词过滤该集合。我使用Guava 来完成所有这些,但当然还有其他(通常更复杂)的方法来实现它。
这是我的产品对象:
public class Product implements Comparable<Product>{
private final String manufacturer;
private final String model;
private final String platform;
public Product(final String manufacturer,
final String model,
final String platform){
this.manufacturer = manufacturer;
this.model = model;
this.platform = platform;
}
public String getManufacturer(){
return manufacturer;
}
public String getModel(){
return model;
}
public String getPlatform(){
return platform;
}
@Override
public int hashCode(){
return Objects.hashCode(manufacturer, model, platform);
}
@Override
public boolean equals(final Object obj){
if(obj instanceof Product){
final Product other = (Product) obj;
return Objects.equal(manufacturer, other.manufacturer)
&& Objects.equal(model, other.model)
&& Objects.equal(platform, other.platform);
}
return false;
}
@Override
public int compareTo(final Product o){
return ComparisonChain
.start()
.compare(manufacturer, o.manufacturer)
.compare(model, o.model)
.compare(platform, o.platform)
.result();
}
}
现在我只需使用 TreeSet<Product> 并在其上应用视图。这是一个返回按模型过滤的实时视图的示例方法:
public static Collection<Product> filterByModel(
final Collection<Product> products,
final String model){
return Collections2.filter(products, new Predicate<Product>(){
@Override
public boolean apply(final Product product){
return product.getModel().equals(model);
}
});
}
像这样使用它:
Collection<Product> products = new TreeSet<Product>();
// add some products
Collection<Product> filtered = filterByModel(products, "A1");
更新:我们可以更进一步,只使用一个集合,由链式谓词支持,而链式谓词又与视图支持的模型相关联。脑袋疼?看看这个:
// this is the collection you sent to your view
final Collection<Product> visibleProducts =
Collections2.filter(products, Predicates.and(Arrays.asList(
new ManufacturerPredicate(yourViewModel),
new ModelPredicate(yourViewModel),
new PlatformModel(yourViewModel)))
);
yourViewModel 是一个由表单控制器返回的值支持的对象。每个谓词使用这个模型对象的一个字段来决定它是否适用。
例如ModelPredicate 检查集合中的所有产品,以查看其型号是否在所选产品中。由于这使用了and 逻辑,因此您可以将其设为层次结构(如果制造商谓词返回 false,则永远不会调用模型和平台谓词)。