2013-04-16 65 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; 
    } 

    ... 
} 

注意,實例化參數對象將需要一些臨時的內存消耗,但他們應該收集垃圾很輕鬆了。