この質問をすることで、どの項目がレポート間で同じになるかを事前に判断することを妨げる、ランタイムの未知数があると思います。それ以外の場合は、同じインスタンスを直接参照できます。
「同等の」インスタンスをキャッシュするフライウェイト スタイルのファクトリは、メモリ フットプリントの削減に役立ちます。それぞれが、特定のデータフィールドをカプセル化し、 「同等」が何を意味するかを定義するために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;
}
...
}
パラメータ オブジェクトのインスタンス化には一時的なメモリの消費が必要になることに注意してください。ただし、ガベージ コレクションは簡単に行うことができます。