我认为通过询问这个问题,有一些运行时未知因素会阻止您事先确定哪些项目在报告中是相同的。否则,你可以直接引用相同的实例。
缓存“等效”实例的轻量级风格工厂可以帮助减少内存占用量。每个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)模式。 –