我認爲通過詢問這個問題,有一些運行時未知因素會阻止您事先確定哪些項目在報告中是相同的。否則,你可以直接引用相同的實例。
緩存「等效」實例的輕量級風格工廠可以幫助減少內存佔用量。每個ReportComponent
都需要某種參數對象來封裝它們的特定數據字段並實現equals()
來定義「等效」的含義。
public class ReportComponentFactory {
private final Map<String, ReportComponent> headerCache =
new HashMap<String, ReportComponent>();
private final Map<GraphParameters, ReportComponent> graphCache =
new HashMap<GraphParameters, ReportComponent>();
public ReportComponent buildHeader(String headerText){
if (this.headerCache.containsKey(headerText)){
return this.headerCache.get(headerText);
}
Header newHeader = new Header(headerText);
this.headerCache.put(headerText, newHeader);
return newHeader;
}
public ReportComponent buildGraph(GraphParameters parameters){
if (this.graphCache.containsKey(parameters)){
return this.graphCache.get(parameters);
}
Graph newGraph = new Graph(parameters);
this.graphCache.put(newGraph);
return newGraph;
}
...
}
注意,實例化參數對象將需要一些臨時的內存消耗,但他們應該收集垃圾很輕鬆了。
查看[Decorator](http://en.wikipedia.org/wiki/Decorator_pattern)模式。 –