Android设计模式(一)--完美单例模式

Android完美单例模式:

以前写的单例模式考虑不完全;

面试的时候,考到这样的问题;

想到这么的问题,居然也会出现,只是后面才发现自己写的单例,太过幼稚;

所以到网上找了一些资料,重新写一个;


单例模式:

可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。


分为:懒汉式单例、饿汉式单例、登记式单例三种;


懒汉式:用到的时候再加载;

饿汉式:一开始就加载;

登记式:使用Map等,登记对象是否实例化;有,则返回对象,无则实例化对象;


线程安全与否,在于懒汉式是否加上同步,或者是实例化时加锁操作;


package com.example.demo;

public class HttpUtils {
	//volatile的作用是: 作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值.
	//一个定义为volatile的变量是说这变量可能会被意想不到地改变,
	//这样,编译器就不会去假设这个变量的值了。
	//精确地说就是,优化器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存器里的备份。
	private volatile static HttpUtils instance;
	
	private HttpUtils()
	{
		//构造函数 逻辑处理 
	}

	public static HttpUtils getInstance()
	{
		//第一次判断是否为空
		if(instance==null)
		{
			synchronized (HttpUtils.class) {//锁
				//第二次判断是否为空 多线程同时走到这里的时候,需要这样优化处理
				if(instance ==null)
				{
					instance =new HttpUtils();
				}
			}
		}
		return instance;
	}
}

单例模式,在Android Framework 中运用广泛;

比如说:

1、输入法管理  InputMethodManager

2、View获得点击、焦点、文字改变等事件的分发管理  AccessibilityManager


public final class InputMethodManager {
    static final boolean DEBUG = false;
    static final String TAG = "InputMethodManager";

    static final String PENDING_EVENT_COUNTER = "aq:imm";

    static InputMethodManager sInstance;

    InputMethodManager(IInputMethodManager service, Looper looper) {
        mService = service;
        mMainLooper = looper;
        mH = new H(looper);
        mIInputContext = new ControlledInputConnectionWrapper(looper,
                mDummyInputConnection, this);
    }

    /**
     * Retrieve the global InputMethodManager instance, creating it if it
     * doesn't already exist.
     * @hide
     */
    public static InputMethodManager getInstance() {
        synchronized (InputMethodManager.class) {
            if (sInstance == null) {
                IBinder b = ServiceManager.getService(Context.INPUT_METHOD_SERVICE);
                IInputMethodManager service = IInputMethodManager.Stub.asInterface(b);
                sInstance = new InputMethodManager(service, Looper.getMainLooper());
            }
            return sInstance;
        }
    }
    
    /**
     * Private optimization: retrieve the global InputMethodManager instance,
     * if it exists.
     * @hide
     */
    public static InputMethodManager peekInstance() {
        return sInstance;
    }
}



 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章