使用Singleton类初始化/访问ArrayList
我在我的应用程序中使用ArrayList。
我想知道从Singleton类初始化ArrayList的确切过程。
该数据将用于其他一些活动。
有人可以帮助了解Singleton类吗?
以下是如何创建单例类:
public class YourSingleton { private static YourSingleton mInstance; private ArrayList list = null; public static YourSingleton getInstance() { if(mInstance == null) mInstance = new YourSingleton(); return mInstance; } private YourSingleton() { list = new ArrayList (); } // retrieve array from anywhere public ArrayList getArray() { return this.list; } //Add element to array public void addToArray(String value) { list.add(value); } }
您需要调用arrayList的任何地方:
YourSingleton.getInstance().getArray();
要向arrays使用添加元素:
YourSingleton.getInstance().addToArray("first value");
要么
YourSingleton.getInstance().getArray().add("any value");
请查看以下wikipedia-artikle:
https://en.wikipedia.org/wiki/Singleton_pattern
但请记住,单身人士是“全球状态”,并使您的源代码难以测试。 有很多人说:“单身人士是邪恶的”
我想你需要这样的东西。
public class SingletonClass { private static ArrayList strArray; private static SingletonClass singleton; private SingletonClass(){} public static synchronized SingletonClass getConnectionInstance(ArrayList strArray){ if (singleton == null) { singleton = new SingletonClass(); } this.strArray = strArray; return singleton; } }