长时间阅读/第一次海报。我是新来的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
}
}
还是有更好的办法?提前道歉,如果它是一个愚蠢的问题。
我想创建为每个项目类型“管理器”,并获得从'地图<类,ManagerInterface>'对应的管理器对象:'managerMap.get(event.class)。管理(事件,时间线);' –
使用时间戳(以秒/毫秒为单位)作为事件hashmap中的键,然后获取此键集,按日期对其进行排序并使用此排序列表访问事件列表? –