百度上很多关于单例模式的解释,例如懒汉模式,饿汉模式等等之类,也有说单例模式与SharedPreferences一起使用,因为SharedPreferences暂不支持多线程访问。可以查看我这篇文章Android sharedpreferences轻量级存储 中介绍SharedPreferences。
下面贴代码看看单例模式与SharedPreferences一起使用。
import android.content.Context; import android.content.ContextWrapper; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class ProgramConfigManage { // 单例模式类对象 private ContextWrapper mWrapper = null; private static ProgramConfigManage m_ProgramConfig = null; private SharedPreferences mPreferences = null; // 将配置参数定义为成员全局变量 private String mstrNetworkIP; private int mnNetworkPort; private String mstrNetworkUserName; private String mstrNetworkPassword; private String mstrNetworkUpdate; // 单例模式获取实例 public static ProgramConfigManage GetInstance(Context base) { if (m_ProgramConfig == null) { m_ProgramConfig = new ProgramConfigManage(base); // 为了提高速度,在这 里读取配置 m_ProgramConfig.mstrNetworkIP = m_ProgramConfig.mPreferences .getString("Config_NetworkIP", ""); m_ProgramConfig.mnNetworkPort = m_ProgramConfig.mPreferences .getInt("Config_NetworkPort", 0); m_ProgramConfig.mstrNetworkUserName = m_ProgramConfig.mPreferences .getString("Config_NetworkUserName", ""); m_ProgramConfig.mstrNetworkPassword = m_ProgramConfig.mPreferences .getString("Config_NetworkPassword", ""); m_ProgramConfig.mstrNetworkUpdate = m_ProgramConfig.mPreferences .getString("Config_NetworkUpdate", ""); } return m_ProgramConfig; } // 配置getSharedPreferences public ProgramConfigManage(Context base) { // super(base); mWrapper = new ContextWrapper(base); mPreferences = mWrapper.getSharedPreferences("Perference", ContextWrapper.MODE_PRIVATE); } // 设置 public void setNetworkState(String strNetworkIP, int nNetworkPort, String strNetworkUserName, String strNetworkPassword) { Editor editor = mPreferences.edit(); editor.putString("Config_NetworkIP", strNetworkIP); editor.putInt("Config_NetworkPort", nNetworkPort); editor.putString("Config_NetworkUserName", strNetworkUserName); editor.putString("Config_NetworkPassword", strNetworkPassword); editor.commit(); mstrNetworkIP = strNetworkIP; mnNetworkPort = nNetworkPort; mstrNetworkUserName = strNetworkUserName; mstrNetworkPassword = strNetworkPassword; } //设置 public void setNetworkUpdateMessage(String strUpdate) { Editor editor = mPreferences.edit(); editor.putString("Config_NetworkUpdate", strUpdate); editor.commit(); mstrNetworkUpdate=strUpdate; } public String getNetworkIP() { return mstrNetworkIP; } public int getNetworkPort() { return mnNetworkPort; } public String getNetworkUserName() { return mstrNetworkUserName; } public String getNetwordPassword() { return mstrNetworkPassword; } public String getNetworkUpdate() { return mstrNetworkUpdate; } }
欢迎大家交流更多的SharedPreferences以及单例模式的用法.
Android 单例模式与SharedPreferences一起使用
原文地址:http://blog.csdn.net/qq_16064871/article/details/44817227