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().
有沒有真正的缺點?
這兩種情況下的數據都保存在堆/棧中嗎?