2016-10-29 24 views
2

長時間閱讀/第一次海報。我是新來的Java和軟件開發,所以如果這是一個可怕的問題,請原諒我!在哪裏修改基於不同對象類型的java中的列表

我現在有一個叫做ItemsOrderManager類,有項目的對象列表它保持,稱之爲ItemsOrder。當構造ItemsOrderManager類時,此列表以正確的順序與一些默認項目實例化。

然後我有另一個類稱爲時間軸有活動的一個HashMap,其中該事件的日期時間是HashMap中的鍵(即HashMap的日期,事件)。事件有一些擴展它的子類(即EventA,EventB,EventC等),因爲它們做了不同的事情/相互之間略有變化/但共享類似的方法/屬性。

我的問題是ItemsOrderManager類將需要處理的日期順序事件的時間軸,這些事件決定ItemsOrder列表將如何被修改。它會做這樣的事情在列表中找到一個特定的項目,然後:該項目

  • 改變一些屬性,或
  • 之前將它添加一個新的項目,
  • 後添加一個新的項目。

它如何取決於它是什麼類型的事件的更改。

它會是這個樣子:

public class ItemsOrderManager { 

    private List<Item> items = new ArrayList<Item>(); 
    private Timeline timeline; 

    Public ItemsOrderManager() { 
     initialiseItems(); //add items to the items list 
     initialiseTimeline(); //for simplicity i put this here to show the timeline gets initialised/we set the events in it and then sort the hashmap 
     processTimeline(); //again for simplicity just showing we need to then process the timeline which modifies the items list 
    } 
} 

所以我的問題是我應該通過在ItemsOrderManager類使用方法操縱ItemsOrder列表或者我應該在事件類中利用的方法/子類,它將列表作爲參數並在那裏進行操作?或者還有另外一種方法呢?這裏最好的設計實踐是什麼?

因此,要麼:

public void processTimeline() { 
    for (Event event : timeline.getEvents().values()) { 
     if (event instanceof EventA) { 
      //manipulate items list 
     } else if (event instanceof EventB) { 
      //manipulate items list in a different way 
     } else { 
      //manipulate items list in a different way altogether 
     } 
    } 
} 

或者我應該這樣做:

public void processTimeline() { 
    for (Event event : timeline.getEvents().values()) { 
     //call something like event.applyEventToList(this.items); to modify the list or returned the modified list 
    } 
} 

還是有更好的辦法?提前道歉,如果它是一個愚蠢的問題。

+0

我想創建爲每個項目類型「管理器」,並獲得從'地圖<類,ManagerInterface>'對應的管理器對象:'managerMap.get(event.class)。管理(事件,時間線);' –

+0

使用時間戳(以秒/毫秒爲單位)作爲事件hashmap中的鍵,然後獲取此鍵集,按日期對其進行排序並使用此排序列表訪問事件列表? –

回答

1

由於這兩個解決方案的工作,它是由你來選擇其中之一。這更像是一個哲學問題,關於你作爲開發者的原則。例如,一個面向對象的發燒友可能會說,Event類是知道如何操作項目列表的實體,因此第二個代碼段將是選擇。但是,在這種情況下,我個人覺得有一個管絃樂對象來處理這個過程比較簡單,所以我會選擇第一種方法。

順便說一句,你確保

for (Event event : timeline.getEvents().values()) 

迭代器提供了有序的事件?

+0

當然可以!感謝excellend響應隊友! – StCicatriz

相關問題