2013-04-16 23 views
0

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

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

+0

查看[Decorator](http://en.wikipedia.org/wiki/Decorator_pattern)模式。 –

回答

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

    ... 
} 

注意,实例化参数对象将需要一些临时的内存消耗,但他们应该收集垃圾很轻松了。