2011-11-27 67 views
4

我需要找到一個解決方案來保存和訪問大量複雜的全局數據和方法。它必須可以從各種數據類的活動和常規實例變量中訪問。從各地訪問全球數據的解決方案 - 有效

這就是我已經做到的。我只想知道它是否有什麼問題,或者是否有更好的/更清潔的方法。

首先我謹向Application喜歡推薦了許多遍

public class MainDataManager extends Application{ 

    public ... large chunks of data in arrays, lists, sets,.... 

    //static variable for singleton access from within instance variables of other classes 
    public static MainDataManager mainDataManager; 

    //create and init the global data, and store it in the static variable of the class 
    @Override 
     public void onCreate() { 
     super.onCreate(); 
     //in case it should get called more than once for any reason 
     if (mainDataManager == null) { 
      init(); 
      mainDataManager = this; 
      } 
     } 

現在從推薦喜歡到處活動中訪問它...

MainDataManager mainDataManager = (MainDataManager)getApplicationContext(); 

而且因爲我需要從正常訪問數據類的實例...

public class MyDataClass { 
    public MainDataManager mainDataManager; 
    public String name; 

    public MyDataClass(String namex) { 
     this.name = namex; 
     //this is why I defined the static variable within MainDataManager, so 
     //one has access to it from within the instance of MyDataClass 
     this.mainDataManager = MainDataManager.mainDataManager; 
    } 

     public void examplesForAccessing() { 
     //some examples on how to access the global data structure and associated methods 
     mainDataManager.someMethodAccess(); 
     xyz = mainDataManager.someDataAccess; 
     mainDataManager.someIndirectMethodAccess.clear(); 
     mainDataManager.someOtherData = false; 
    } 
} 

因爲我有n到目前爲止這樣做,我想知道這是否有任何問題。內存,效率,...

非常感謝!

我可以添加一個小旁註嗎? 我也可以使用MainDataClass的類MainDataClass.var or MainDataClass.method().有沒有真正的缺點?

這兩種情況下的數據都保存在堆/棧中嗎?

回答

0

您對「大塊數據」沒有給出太多細節,但請記住,onCreate方法是您的應用程序啓動時運行的第一件事情,它在主/ UI線程上運行。這意味着如果你在你的init()方法中做了很長時間的任務,那麼你的UX將會很差,更不用說你冒着ANR異常的風險。

該解決方案很簡單:

  1. 保持你的onCreate短
  2. 創建一個BG線程,並用它來運行所有的初始化代碼
  3. 顯示「撲通」 /「歡迎」屏幕BG線程運行時的正確進度條。
相關問題