2011-07-05 122 views
1

在我的代碼中,我有一個List<Person>。屬性在此列表中的對象可以包括沿着線的東西:創建方法過濾器

  • ID

在我的應用程序的一部分,我將被允許用戶通過使用這三個值的任何組合來搜索特定人員。目前,我有一個switch語句,簡單地檢查填充了哪些字段,並調用爲該組合值指定的方法。

即:

switch typeOfSearch  
if 0, lookById()  
if 1, lookByIdAndName() 
if 2, lookByFirstName() 

等。實際上有7種不同的類型。

這使得我有一種方法爲每個語句。這是做這件事的'好'方法嗎?有沒有一種方法可以使用參數或某種「過濾器」?它可能沒有什麼區別,但我用Java編寫了這個代碼。

回答

3

你可以做一些更優雅的地圖和界面。試試這個例如,

interface LookUp{ 
    lookUpBy(HttpRequest req); 
} 

Map<Integer, LookUp> map = new HashMap<Integer, LookUp>(); 

map.put(0, new LookUpById()); 
map.put(1, new LookUpByIdAndName()); 

...

控制器那麼你可以做

int type = Integer.parseInt(request.getParameter(type)); 
Person person = map.get(type).lookUpBy(request); 

這種方式可以快速查找的方法與地圖。當然,你也可以使用一個長開關,但我覺得這更易於管理。

0

如果好意思是「語言對我來說」,否。

如果好意味着'可讀',我會在Person中定義一個方法match(),如果該對象符合您的搜索條件,則返回true。此外,可能是創建方法標準的一種好方法,您可以在其中封裝搜索條件(您要查找哪些字段以及哪個值)並將其傳遞至匹配條件(標準條件)。

0

這種做法很快就變得難以管理,因爲組合的數量很快就會變得巨大。 創建擁有所有可能的查詢參數的PersonFilter類,並訪問列表中的每個人:

private class PersonFilter { 
    private String id; 
    private String firstName; 
    private String lastName; 

    // constructor omitted 

    public boolean accept(Person p) { 
     if (this.id != null && !this.id.equals(p.getId()) { 
      return false; 
     } 
     if (this.firstName != null && !this.firstName.equals(p.getFirstName()) { 
      return false; 
     } 
     if (this.lastName != null && !this.lastName.equals(p.getLastName()) { 
      return false; 
     } 

     return true; 
    } 
} 

過濾現在由

public List<Person> filter(List<Person> list, PersonFilter filter) { 
    List<Person> result = new ArrayList<Person>(); 
    for (Person p : list) { 
     if (filter.accept(p) { 
      result.add(p); 
     } 
    } 
    return result; 
} 
0

實現在某些時候,你應該看一看的東西像Lucene這將爲您提供此類搜索的最佳可擴展性,可管理性和性能。不知道你處理的數據量只有只有建議這是一個更長期的解決方案與更大的對象搜索。這是一個了不起的工具!