Coding style 避免if-else条件的代码解决方案

Coding style 避免if-else条件的代码解决方案,coding-style,Coding Style,我想知道是否有人可以建议我一个设计模式或最好的方式来编码下面的问题 1) 我有一系列的书,如下所示 list.add(new Book(title, author); list.add(new Book(title1, author1); 等等 2) 现在我想按作者查找列表中的所有书籍 findByAuthor(String author) { for(Book book : list){ if(book.getAuthor().equals(author)){ ret

我想知道是否有人可以建议我一个设计模式或最好的方式来编码下面的问题

1) 我有一系列的书,如下所示

list.add(new Book(title, author);
list.add(new Book(title1, author1);
等等

2) 现在我想按作者查找列表中的所有书籍

findByAuthor(String author) {
  for(Book book : list){
    if(book.getAuthor().equals(author)){
      return book;
    }
  }
}
像wise一样,我还有另一个方法叫做findbytle()。但是,除了book.getAuthor()必须是book.getTitle()之外,它将是相同的代码。一切都会一样

3) 现在我可以编写一个对这两种方法都通用的方法,如下所示

findByBookProperty (String type, String propertyValue){
  for(Book book : list)
    if(type.equals("author") && book.getTitle().equals(propertyValue)){
      return book;
    } //another else if for author
    //another else for another property
    // if else repeats for all the required finder types...
  }
}
4) 我这里的问题是; 1.我不想对查找器类型使用恶劣的if/else条件。 2.我想知道是否有任何设计模式或更好的方法来处理这个if-else或swich方法

重要提示:我在spring控制器方法中获得作者姓名作为请求参数值


感谢您的想法。

使用Commons Collections的谓词框架:

1) 为每种类型的测试构造一个
谓词
实例

2) 使用
CollectionUtils.select()
,传入要用于计算对象的谓词

另一种选择是使用Commons Collections的转换框架:

1) 为要提取/比较的每种类型的属性编写一个
转换器


2) 编写一个通用循环,接受一个
Transformer
实例作为参数。

这可能会有所帮助。这实际上是Commons Collections的一个不太为人所知的特性,它非常有用,令人目瞪口呆。请注意,您的代码不会按作者返回所有书籍,而只返回第一本