android设计模式之单例模式详解

2019-12-10 20:08:07王冬梅

            return mSearchManager;
        }
        return super.getSystemService(name);
    }

 

其实这里getSystemService我们可以看做一个特殊的决策类,从以下代码来看:

 

复制代码
if (SEARCH_SERVICE.equals(name)) {
            ensureSearchManager();
            return mSearchManager;
        }

 

我们改成:

 

复制代码
public static SearchManager getInstance(){
     ensureSearchManager();
     return mSearchManager;
}

 

这就是一个单例模式。但从getSystemService整个代码来看,确实工厂方法模式,这个我们在下面会讲到。

根据对象创建时机的不同,单例模式有三种方式:

1、饿汉式    --就是实例在类加载的时候就生成

 

复制代码
public class foo{
        foo(){}
        private static foo instance =new foo();
        public static foo getlnstance(){
           return instance;
        }
}

 

2、懒汉式

 

复制代码
public class foo{
        foo(){}
        private static foo instance = null ;
        public static foo getlnstance(){
            if(instance == null){
                instance = new foo();
            }
           return instance;