Pregunta

I am implementing a report that will use different components ie some have header, footer table. Another has header, title, table, graph. I have implemented this using a similar pattern to the strategy pattern. I can generate an report using the same class report, and have an interface defined Component( onDraw ). Which each component implements Table, Graph etc...

But for memory consumption and good software design I dont want to have to create duplicate tables and headers if they are being used on each report with the same data. Is there a pattern that I can use to save the drawn table and header down from one report and re use for the other report? I have been looking at the fly weight pattern. Or using static variables on the class report. Issue with this is when I want to use different data on the report class.

¿Fue útil?

Solución

I assume that by asking this question there are runtime unknowns that prevent you from determining in advance which items will be the same across reports. Otherwise you could just reference the same instances directly.

A flyweight-style factory that caches "equivalent" instances could help reduce memory footprint. Each ReportComponent would need some sort of parameter object to encapsulate their particular data field(s) and implement equals() to define just what "equivalent" means.

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;
    }

    ...
}

Note that instantiating parameter objects will require some temporary memory consumption, but they should be garbage collected easily enough.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top