设计模式之单例模式

来源:《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());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章