做开发的朋友肯定对单例模式不陌生,大概有下面两种实现方式。
public class Singleton{
private static Singleton instance = null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
public class Singleton{
private static Singleton instance=new Singleton();
private Singleton(){
}
public static Singletonget Instance(){
return instance;
}
}
但是在我们Android中,经常会使用到Context的引用,于是你写下下面这种单例
public class Singleton{
private static Singleton instance = null;
private Singleton(Context ctx){
}
// Context 参数
public static synchronized Singleton getInstance(Context ctx){
if(instance == null){
instance = new Singleton(ctx);
}
return instance;
}
}
每次获取单例的时候都要传入一个Context对象,如果我们要在纯Java类下使用,岂不是就歇菜了?
所以正确的单例模式应该是这样的,以PreferenceUtils为例
我们只需要在Application里面调用createInstance(Context ctx),在其他地方使用的时候只需要getInstance()即可
package cn.gavinliu.formater.util;
import java.util.Map.Entry;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
public class PreferenceUtils {
private static PreferenceUtils util;
private SharedPreferences mPreference;
public static void createInstance(Context ctx) {
util = new PreferenceUtils(ctx);
}
public static PreferenceUtils getInstance() {
return util;
}
private PreferenceUtils(Context ctx) {
mPreference = ctx.getApplicationContext().getSharedPreferences(ctx.getPackageName() + "_preferences", Context.MODE_PRIVATE);
}
public boolean putString(String key, String value) {
return mPreference.edit().putString(key, value).commit();
}
public boolean putInt(String key, int value) {
return mPreference.edit().putInt(key, value).commit();
}
public boolean putBoolean(String key, boolean value) {
return mPreference.edit().putBoolean(key, value).commit();
}
public boolean putValues(ContentValues values) {
SharedPreferences.Editor editor = mPreference.edit();
for (Entry<String, Object> value : values.valueSet()) {
editor.putString(value.getKey(), value.getValue().toString());
}
return editor.commit();
}
public String getString(String key) {
return getString(key, "");
}
public String getString(String key, String defValue) {
return mPreference.getString(key, defValue);
}
public int getInt(String key) {
return getInt(key, -1);
}
public int getInt(String key, int defValue) {
return mPreference.getInt(key, defValue);
}
public boolean getBoolean(String key) {
return getBoolean(key, false);
}
public boolean getBoolean(String key, boolean defValue) {
return mPreference.getBoolean(key, defValue);
}
}