繁体   English   中英

策略模式重用数据以创建报告

[英]Strategy Pattern reusing data to create a report

我正在实现一个报告,该报告将使用不同的组件,即某些组件具有页眉,页脚表。 另一个具有标题,标题,表格,图形。 我已经使用与策略模式类似的模式来实现了这一点。 我可以使用相同的类报告生成报告,并具有定义了Component(onDraw)的接口。 每个组件都实现表格,图形等...

但是,由于内存消耗和良好的软件设计,如果在具有相同数据的每个报表上使用重复的表和标头,我就不必创建重复的表和标头。 有没有一种模式可以用来将绘制的表格和标题从一个报表中保存下来,然后再用于另一个报表? 我一直在看苍蝇的体重模式。 或在类报告上使用静态变量。 问题是当我想在报表类上使用其他数据时。

我假设通过问这个问题,存在运行时未知数,这些未知数使您无法提前确定报表中哪些项目相同。 否则,您可以直接直接引用相同的实例。

缓存“等效”实例的flyweight风格的工厂可以帮助减少内存占用。 每个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;
    }

    ...
}

请注意,实例化参数对象将需要一些临时内存消耗,但是应该足够容易地对其进行垃圾回收。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM