2012-02-01 56 views
3

我有一個需要處理傳入的對象服務的方法:(順便說一句,這是僞代碼)我怎樣才能提高此實現更有效率

public class IncomingParentObject { 
    public Collection<IncomingChildOject> childObjects; 
} 

public Class IncmoingChildObject { 
    public String name; 
} 

我有一個「註冊表」關心傳入子對象子集的「客戶」。在註冊時,我們只知道「名稱」。客戶端對象封裝傳輸層將信息轉發給的詳細信息。

public class Registry { 
    // String represents the name in the child object 
    public Map<String, Set<Client>> clients; 
} 

眼下服務類是沿此線的東西:

public void processIncmoingParentObject(IncomingParentObject parentObject) { 
    for (IncmoingChildObject childObject : parentObject.childObjects) { 
     Set<Client> clients = registry.clients.get(childObject.name); 

     for (Client client : clients) { 
      this.transportLayer.transportChildObject(childObject, client); 
     } 
    } 
} 

這導致多次打電話給傳送層(可能是昂貴的或及時)。我希望將此基本上減少爲ChildObjects子集中每個客戶端的一個傳輸。

transportLayer.transport(Client client, Set<IncmoingChildObject> childObjects); 

將一個effiecent莊園是通過什麼父母子女進行掃描,以確定孩子的一個子集發送到客戶端。

+0

這會是更好的CodeReview.SE? – 2012-02-01 16:44:22

+0

我不知道那是什麼。 – predhme 2012-02-01 16:46:56

+0

這是一個StackExchange方面特別爲代碼review.Link:http://codereview.stackexchange.com/我認爲它可能會得到更多/更好的答案,但它看起來像你在這裏得到的答案。 – 2012-02-01 17:01:53

回答

3

我會用地圖來跟蹤Set<IncomingChildObject>每個Client

在未經測試的Java:

public void processIncomingParentObject(IncomingParentObject parentObject) { 
    Map<Client,Set<IncomingChildObject>> childObjectsByClient = 
     new Map<Client,Set<IncomingChildObject>>(); 
    for (IncomingChildObject childObject : parentObject.childObjects) { 
     Set<Client> clients = registry.clients.get(childObject.name); 
     for (Client client : clients) { 
      Set<IncomingChildObject> childObjects = 
       childObjectsByClient.get(client); 
      if (childObjects == null) { 
       childObjects = new Set<IncomingChildObject>(); 
       childObjectsByClient.put(client, childObjects); 
      } 
      childObjects.add(childObject); 
     } 
    } 
    for (Entry<Client,Set<IncomingChildObject>> e : childObjectsByClient.entrySet()) { 
     this.transportLayer.transport(e.getKey(), e.getValue()); 
    } 
} 
+0

完美,謝謝 – predhme 2012-02-01 17:01:52

1

那麼,你可以建立一個地圖名稱 - >兒童列表,然後迭代列表並獲取地圖中每個鍵的客戶端。然後將該客戶端和地圖項的子項列表傳遞給傳輸層。

爲此,您可以嘗試在Apache Commons Collections項目中使用Multimap實現中的一個(它不支持泛型,但有第三方端口可以使用,或者嘗試使用Google Guava,但我不知道是否它提供了一個multimap)。

+0

當然番石榴提供了一個'Multimap',它被完全基因化並且在JDK集合中表現良好。 ;) – 2012-02-01 16:53:17

+0

@Louis謝謝你的信息:) – Thomas 2012-02-01 16:55:06

+0

我看看他們謝謝。 – predhme 2012-02-01 17:01:44