做开发的朋友肯定对单例模式不陌生,大概有下面两种实现方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Singleton{

private static Singleton instance = null;

private Singleton(){

}

public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton{

private static Singleton instance=new Singleton();

private Singleton(){

}

public static Singletonget Instance(){
return instance;
}

}

但是在我们 Android 中,经常会使用到 Context 的引用,于是你写下下面这种单例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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()即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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);
}
}