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

时间:2013-04-16 20:50:31

标签: java c++ design-patterns flyweight-pattern

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

但是对于内存消耗和良好的软件设计,如果在具有相同数据的每个报表上使用它们,我不希望创建重复的表和标题。是否有一种模式可用于从一个报告中保存绘制的表格和标题并重新用于其他报告?我一直在看飞重模式。或者在类报告中使用静态变量。问题是当我想在报告类上使用不同的数据时。

1 个答案:

答案 0 :(得分:0)

我认为通过询问这个问题,有一些运行时未知因素会阻止您事先确定哪些项目在报告中是相同的。否则你可以直接引用相同的实例。

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

    ...
}

请注意,实例化参数对象需要一些临时内存消耗,但它们应该很容易被垃圾收集。