開發(fā)中我們有時(shí)候需要在APP運(yùn)行中存儲(chǔ)一些數(shù)據(jù)纤勒,存儲(chǔ)在內(nèi)存中拱撵,這時(shí)候創(chuàng)建一個(gè)單例就非常方便篓冲,我只做為筆記發(fā)布,大家隨意看看
public class Singleton {
?? ?//單例模式實(shí)例
?? private static Singleton instance = null;
? ?//synchronized 用于線程安全,防止多線程同時(shí)創(chuàng)建實(shí)例
?? public synchronized static Singleton getInstance(){
????? if (instance == null){
???????? instance = new Singleton();
????? }
?? return instance;
?? }
?? final HashMapmMap;
?? public Singleton(){
????? this.mMap = new HashMap();
?? }
?? public void put(String key,Object value){
?? mMap.put(key,value);
?? }
?? public Object get(String key){
????? return mMap.get(key);
?? }
}
使用:
//初始化單例
Singleton? mSingleton = Singleton.getInstance();
//儲(chǔ)存數(shù)據(jù),或者參數(shù)
mSingleton.put(key,value);
//獲取數(shù)據(jù),或者參數(shù)
mSingleton.get(key);