來源:《Android源碼設計模式解析與實戰》
覺得設計模式比較重要,想慢慢弄,有時間記錄一下,且每個設計都找到分析一個源碼出處來,good,自己擼代碼擼筆記。
思路
一個類能返回對象一個引用(永遠是同一個)和一個獲得該實例的方法(必須是靜態方法,通常使用getInstance這個名稱)
使用場景
需要避免產生多個對象引起資源過多消耗,或者某種類型的只應該有且只有一個
Code
- 單例
public class Singleton {
static Singleton instance;
static final Object syncLock = new Object();
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (syncLock) {
instance = new Singleton();
}
}
return instance;
}
public String doSomething() {
String ret = "singleton method";
System.out.println(ret);
return ret;
}
}
- 調用
Log.d(TAG, Singleton.getInstance().doSomething());
實際場景舉一例
控件TextView設置超鏈接
android.text.method.ScrollingMovementMethod
public class ScrollingMovementMethod extends BaseMovementMethod implements MovementMethod {
// ...
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new ScrollingMovementMethod();
return sInstance;
}
private static ScrollingMovementMethod sInstance;
}
- use
textView.setMovementMethod(ScrollingMovementMethod.getInstance());