设计模式之单例模式+LayoutInflater分析

单例模式

  • 单例模式是应用最广的模式之一,在应用这个模式时,单例对象的类必须保证只有一个实例存在,许多时候整个系统只需要拥有一个全局变量,这样有利于我们协调系统整体的行为
  • 定义:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例
  • 使用场景:当创建一个对象需要消耗的资源太多的时候,如要访问IO和数据库等资源的时候,就可以考虑使用单例模式
  • UML类图
    这里写图片描述
  • 角色介绍
  • Client:高层客户端
  • Singleton:单例类
  • 特点(关键点):
  • 构造方法不对外开放,private
  • 通过一个静态类或者枚举返回单例类的对象
  • 确保单例类的对象有且只有一个,尤其是在多线程环境下
  • 确保单例类在对象反序列化的时候不会重建对象

简单示例

  • 就拿公司的等级来举例吧,一个公司只能有一个CEO,可以有几个Vp,很多员工
  • 看看代码什么样子
  • 先是公司员工的基类
//员工
public class Worker {
    public void work(){
        System.out.println("work: 干活");
    }
}
  • 也就说我们定义的这个类是公司每个人都必须继承的,这相当于公司凭证一样,再看副总裁类
//副总裁
public class Vp extends Worker {

    @Override
    public void work() {
        super.work();
        //管理下面的经理
    }
}
  • 总裁
//CEO,饿汉单例模式
public class CEO extends Worker {
    private static final CEO mCeo = new CEO();
    //构造方法私有,外部不能new这个对象
    private CEO(){}

    //共有的静态方法,对外暴露获取单例对象的接口
    public static CEO getCeo(){
        return mCeo;
    }

    @Override
    public void work() {
        //管理VP
    }
}
  • 可见总裁使用了单例模式
  • 看看公司类
//公司类
public class Company {
    private final static String TAG = "Company";

    private List<Worker> allWorkers = new ArrayList<>();
    public void addWorker(Worker worker){
        allWorkers.add(worker);
    }

    public void showAllWorkers(){
        for (Worker w : allWorkers) {
            System.out.println("showAllWorkers: worker = " + w.toString());
        }
    }
}
  • 测试

public class Test {
    public static void main(String[] args) {
        Company cp = new Company();
        //CEO对象只能通过getCEO获取
        Worker ceo1 = CEO.getCeo();
        Worker ceo2 = CEO.getCeo();
        cp.addWorker(ceo1);
        cp.addWorker(ceo2);
        //通过new创建Vp对象
        Worker vp1 = new Vp();
        Worker vp2 = new Vp();
        //通过new创建Worker对象
        Worker worker = new Worker();
        Worker worker1 = new Worker();
        Worker worker2 = new Worker();

        cp.addWorker(vp1);
        cp.addWorker(vp2);
        cp.addWorker(worker);
        cp.addWorker(worker1);
        cp.addWorker(worker2);

        cp.showAllWorkers();
    }

}
  • 输出信息
showAllWorkers: worker = Singleton.CEO@14ae5a5
showAllWorkers: worker = Singleton.CEO@14ae5a5
showAllWorkers: worker = Singleton.Vp@131245a
showAllWorkers: worker = Singleton.Vp@16f6e28
showAllWorkers: worker = Singleton.Worker@15fbaa4
showAllWorkers: worker = Singleton.Worker@1ee12a7
showAllWorkers: worker = Singleton.Worker@10bedb4
  • 可以看到,我们CEO的两次得到的其实是一个对象,而其他类型的员工是不同的对象,这也就是单例模式
  • 通过私有构造方法加提供得到单例静态对象的方法达到单例的目的

单例模式的其他实现方式

  • 上面使用的 是饿汉方式,也就是在类加载之处就会将单例创建出来,不过并不是这一种方式,我们接下来看看懒汉模式

懒汉方式

public class Singleton(){
    private static Singleton intance;
    private Singleton(){}
    public static synchronized Singleton getIntance(){
        if(intance == null){
            intance = new Singleton();
        }
        return intance;
    }
}
  • 可以看到,我们使用了synchronized 关键字来保证他的线程同步,但是最大的问题是每次调用这个方法的时候都会进行同步,造成不必要的同步开销,一般不建议使用

Double Check Lock实现单例

public class Singleton {

    private static Singleton mInstance = null;
    private Singleton(){}
    public void doSomethings(){
        System.out.println("do thing");
    }

    public static Singleton getsInstance() {
        if(mInstance == null){
            synchronized (Singleton.class){
                if(mInstance == null){
                    mInstance = new Singleton();
                }
            }
        }
        return mInstance;
    }
}
  • 这种方式的两点都在getInstance上面,可以看到这个方法中对单例进行了两次判空,第一层判空是为了不必要的同步,第二层则是为了在null的情况下创建实例

静态内部类单例模式

public class Singleton {
    private Singleton() {
    }

    public static Singleton getInstance(){
        return SingletonHolder.sInstance;
    }

    private static class SingletonHolder{
        private static final Singleton sInstance = new Singleton();
    }
}
  • 当第一次加载Singleton类时不会初始化SInstance,只有在第一次调用Singleton的getInstance方法时才会导致SInstance被初始化,这种方式不仅保证线程安全,也能保证单例模式的准确性,所以推荐使用这种方式

枚举单例

public enum SingletonEnum {
    INSTANCE;
    public void doSomething(){
        System.out.println("do sth");
    }
}
  • 枚举在java中与普通的类是相同的,不就能有自己的字段,也可以有自己的方法,最重要的是枚举实例是默认线程安全的,并且在任何时候他都是一个单例
  • 注意:我们知道,通过序列化可以将一个单例的对象写到磁盘,然后再读回来,从而有效的获得一个实例,即使构造函数是私有的,反序列化依然可以通过特殊的手段去创建一个类的新的一个实例,反序列化操作提供了一个很特别的钩子函数,类中具有一个私有的readResolve方法,这个方法可以让开发人员控制对象的反序列化,例如,上面几个实例中,为了杜绝对象在反序列化的时候重新生成对象,必须加入这个方法
public final class Singleton implements Serializable{

    private static final long serialVersionUID = 0l;
    private static final Singleton INSTANCE = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return INSTANCE;
    }

    private Object readResolve() throws ObjectStreamException{
        return INSTANCE;
    }
}
  • 这里就是在反序列化的时候将单例对象返回,而不是重新生成一个新的对象,而对于枚举,并不存在这个问题,这里有两点需要注意:
  • 1.可序列化类中的字段类型不是java的内置类型,那么该字段类型也需要实现Serializable接口
  • 2.如果你调整了可序列化类的内部结构(新增或者去除某个字段),但没有修改serialVersionUID ,那么会引发异常或者导致某个属性为0或者null,此时最好的方案就是将serialVersionUID 的值设置为0L,这样我们修改了类的结构时,那些新修改的字段会为0或者null;

使用容器实现单例模式

public class SingletonManager {
    private static Map<String ,Object> objectMap = new HashMap<>();

    private SingletonManager(){}

    public static void registerService(String key,Object instance){
        if(!objectMap.containsKey(key)){
            objectMap.put(key,instance);
        }
    }

    public static Object getService(String key){
        return objectMap.get(key);
    }
}
  • 这种方式通过一个Map来管理所有的单例类,并且通过Map的特性我们知道只能存在一个单例
  • 不管使用哪种单例模式,他们的核心都是将构造方法私有化,然后通过静态方法获取唯一的单例对象,在这个过程中必须保证线程安全,防止反序列化重新生成新对象等,具体方式还是取决于代码环境

Android源码中的单例模式

  • 在Android系统中,我们经常会通过Context获取系统级别的服务,如:WindowsManagerService,ActivityManagerService等,更常用的是一个LayoutInflater的类,这些服务会在合适的时候以单例的形式注册在系统中,在我们需要的时候就通过Context的getSystemService(String name)来获取,我们以LayoutInflater为例来说明
  • 平时大概会这么用到LayoutInflater
LayoutInflater.from(mContext).inflate(R.layout.view,null);
  • 通过LayoutInflater.from(mContext)方法来获取LayoutIn服务,我们看看from方法的实现
public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }
  • 可以看到在内部调用的是context.getSystemService来获取服务,那么跟踪进Context类,发现
public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);
  • 这里只是一个抽象方法,那么我们使用的Context对象到底是个什么东西呢?
  • 事实上,在Application,Activity,Service中都会存在一个Context对象,即Context的总个数是Activity的个数 + Service的个数 + 1(这个1是一个Android程序只能有一个Application),而View一般都是由activity来显示,我们选择Activity的Context来分析
  • 我们知道一个Activity的入口是ActivityThread的main函数,在main函数中创建一个新的ActivityThread对象,并且启动消息循环(UI线程),创建新的Activity,新的Context对象,然后将该Context对象传递给Activity,下面看看ActivityThread的源码
public static void main(String[] args) {
//代码省略
        ....
        Process.setArgV0("<pre-initialized>");
//主线程的消息循环
        Looper.prepareMainLooper();
//创建ActivityThread对象
        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        //开启消息轮询
        Looper.loop();
    }


private void attach(boolean system) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
        //如果不是系统应用的情况
            ViewRootImpl.addFirstDrawHandler(new Runnable() {
                @Override
                public void run() {
                    ensureJitEnabled();
                }
            });
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            final IActivityManager mgr = ActivityManager.getService();
            try {
            //AMS关联mAppThread(ApplicationThread)
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            //以下省略
}
  • 在main方法中,我们创建一个ActivityThread对象之后,调用attach方法参数为false(代表不是系统应用),然后会通过Binder机制与AMS绑定之后通信,并且通过Handler在主线程最终调用handleLaunchActivity方法,我们看一下这个方法的实现
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
     //所有的代码省略,在这里创建出Activity对象
        Activity a = performLaunchActivity(r, customIntent);
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

//这里创建Context
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
        }

        try {
        //创建Application
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }

                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                appContext.setOuterContext(activity);
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);

        return activity;
    }

private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {

        ContextImpl appContext = ContextImpl.createActivityContext(
                this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);

        return appContext;
    }
  • 这里我将大部分代码都省略,我们可以看到在activity中的Context的实现类是ContextImpl ,刚才我们是看他的getSystemService方法,所以这里我们直接去看ContextImpl的getSystemService方法
public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }
  • 跟进去,SystemServiceRegistry类的getSystemService方法
public static Object getSystemService(ContextImpl ctx, String name) {
        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return fetcher != null ? fetcher.getService(ctx) : null;
    }
  • 这里的SYSTEM_SERVICE_FETCHERS的声明如下:
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =new HashMap<String, ServiceFetcher<?>>();
  • 可见,这里的HashMap存放的是String和ServiceFetcher的键值对,key是服务的名称,那么值就是ServiceFetcher了,通过这个HashMap找到ServiceFetcher,然后通过ServiceFetcher找到服务,这里的ctx是来自ContextImpl的,而我们知道ContextImpl是在ActivityThread中调用的,所以这里通过ServiceFetcher.getService获取到当前Activity对应的Service
  • 可是我点进去发现ServiceFetcher竟然SystemServiceRegistry的内部接口
static abstract interface ServiceFetcher<T> {
        T getService(ContextImpl ctx);
    }
  • 那他的实现类呢?最后,无奈,在SystemServiceRegistry的静态常量区发现了这段代码
  • 这是一段700多行的静态区,执行的全是RegisterService方法,太长…….
  • 还记得我们之前要找的东西嘛?
LayoutInflater LayoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  • 那么这里通过Context.LAYOUT_INFLATER_SERVICE在SystemServiceRegistry类里面一搜索,直接就定位到了我们想要的东西
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
                new CachedServiceFetcher<LayoutInflater>() {
            @Override
            public LayoutInflater createService(ContextImpl ctx) {
                return new PhoneLayoutInflater(ctx.getOuterContext());
            }});
  • 我们先看一下registerService方法
private static <T> void registerService(String serviceName, Class<T> serviceClass,
            ServiceFetcher<T> serviceFetcher) {
        SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
        SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
    }
  • 他将我们的参数放在了SYSTEM_SERVICE_FETCHERS这个Map 中,
  • 所以说当调用SYSTEM_SERVICE_FETCHERS.get(name);得到的是上面这个注册方法里面的内部实现类CachedServiceFetcher()对象,当调用fetcher.getService(ctx)这个方法,我们先去看看这个getService是干嘛的
static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
        private final int mCacheIndex;

        public CachedServiceFetcher() {
            mCacheIndex = sServiceCacheSize++;
        }

        @Override
        @SuppressWarnings("unchecked")
        public final T getService(ContextImpl ctx) {
            final Object[] cache = ctx.mServiceCache;
            synchronized (cache) {
                // Fetch or create the service.
                Object service = cache[mCacheIndex];
                if (service == null) {
                    try {
                    //看到了吗?到这里调用的就是我们刚才重新的createService方法
                        **service = createService(ctx);**
                        cache[mCacheIndex] = service;
                    } catch (ServiceNotFoundException e) {
                        onServiceNotFound(e);
                    }
                }
                return (T)service;
            }
        }

        public abstract T createService(ContextImpl ctx) throws ServiceNotFoundException;
    }
  • 明白了吧?这里就会返回我们刚才在registerService方法里面那个匿名内部类的重写的createService方法返回的new PhoneLayoutInflater(ctx.getOuterContext());
  • 而我们SYSTEM_SERVICE_FETCHERS他是一个HashMap可知,这种方式是单例模式的容器实现

深入理解LayoutInflater

  • LayoutInflater在我们的开发中扮演着重要的角色,但很多时候 我们都不知道它的重要性,因为它的重要性被隐藏在了Activity,Fragment等组件的光环之下
  • LayoutInflater是个抽象类,它的声明如下:
public abstract class LayoutInflater {
  • 通过上面我们也知道了这里得到的是抽象类LayoutInflater的子类PhoneLayoutInflater
  • 我们去看看PhoneLayoutInflater类的实现
public class PhoneLayoutInflater extends LayoutInflater {
//内置View类型的前缀,如TextView的完整路径是android.widget.textView
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };

    public PhoneLayoutInflater(Context context) {
        super(context);
    }

    protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
    }


    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
    //在View名字的前面添加前缀来构造View的完整路径,例如:类名为TextView,那么TextView的完整路径是android.widget.textView
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {}
        }

        return super.onCreateView(name, attrs);
    }

    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}
  • 这个类的代码很少,核心的程序就是重写了LayoutInflater的onCreateView方法,该方法就是先构造出View的完整路径,然后根据类的完整路径构造对应的View对象
  • 那么具体的构造过程呢?为了完整的分析Android构建View的过程,我们以Activity的setContentView为例,来看一下
public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }
  • 我们知道Activity的Window是PhoneWindow,继续跟踪,来到PhoneWindow的SetContextView方法
public void setContentView(int layoutResID) {
//当MContentParent为空时先构建DecorView
//并且将DecorView包裹到MContentParent中
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
        //解析layoutResId
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }
  • 在分析这个解析LayoutResId之前,我们先来看一下Activity的Window的View层级图
    这里写图片描述
  • 系统在构建的时候,会先构建一个MContentParent对象,然后通过LayoutInflater的inflate方法将指定布局的视图添加到mContentParent中,好,我们接着来看LayoutInflater的inflate方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
//获取xml资源解析器
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
  • 然后我们看一下inflate(parser, root, attachToRoot);这个方法
  • 第一个参数是xml解析器,第二个是被解析布局的父布局,第三个是是否要将要解析的布局添加到父视图
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
//
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                //找到根节点
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }

                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();

                if (DEBUG) {
                    System.out.println("**************************");
                    System.out.println("Creating root view: "
                            + name);
                    System.out.println("**************************");
                }
//如果是Merge标签,那就解析
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    //这里通过xml的tag来解析layout的根视图,name是解析的视图的类名,比如说LinearLayout
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        //得到根节点的属性
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                        //如果attachToRoot值为false,那么给temp设置布局参数
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }

//解析temp视图下的所有子视图
                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);

                    if (DEBUG) {
                        System.out.println("-----> done inflating children");
                    }

                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }
  • 上面 的这个方法的代码主要分下面几个部分:
  • 1.解析xml标签中的根标签(第一个元素)
  • 2.如果跟标签是merge,就用rinflate方法解析,这个方法会将merge标签下的所有子View直接添加到跟标签中
  • 3.如果跟标签是普通元素,那么使用createViewFromTag方法对该元素进行解析
  • 4.调用rInflate解析temp跟元素下的所有子View,并将这些子View都添加到temp下
  • 5.返回解析到的根视图


  • 我们先看看createViewFromTag这个方法解析单个标签

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        if (!ignoreThemeAttr) {
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }

        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            return new BlinkLayout(context, attrs);
        }

        try {
            View view;
            //这里的Factory 可以设置LayoutInflater的factory来自行解析View,默认为空
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }
//没有Factory的情况下通过CreateView来创建一个View
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                //内置控件的解析
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                    //自定义控件的解析
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            return view;
    }
  • 这里为什么是通过 “.” (点)来判断是不是内置控件的呢 ?因为内置空间我们一般用的话都是直接写控件名字,而自定义的一般都会写上完整路径
  • 而这里的区别就是内置控件因为我们只写了控件的名字 ,所以还记得嘛?在之前的代码里面有一段是为了给控件加上完整的名字的
private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };
  • 而最终都会调用的是createView来解析,来直接进入createView方法
public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
            //从缓存中获取构造方法
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> clazz = null;

        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

            if (constructor == null) {
            //如果没有缓存构造方法
                // Class not found in the cache, see if it's real, and try to add it
                //如果prefix不为空,那么构造完整的View 路径,并且加载该类
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);

                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
                //从class对象中获取构造方法,并存入缓存
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }

            Object lastContext = mConstructorArgs[0];
            if (mConstructorArgs[0] == null) {
                // Fill in the context if not already within inflation.
                mConstructorArgs[0] = mContext;
            }
            Object[] args = mConstructorArgs;
            args[1] = attrs;
//通过反射构造View
            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            mConstructorArgs[0] = lastContext;
            return view;

        finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }
  • createView相对简单,先将View类加载到虚拟机当中,然后获取该类的构造方法并缓存,再通过构造方法来创建完整的View对象,最后将对象返回,这就是解析单个View的 过程
  • 而我们的V窗口中是一颗树,LayoutInflater需要解析完这棵树,接下来就交给rInflate方法
void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
//获取树的深度,深度优先遍历
        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;
//遍历整个树的元素
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();

            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {//解析include标签
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {//解析Merge标签,抛出异常,因为Merge标签必须为根视图
                throw new InflateException("<merge /> must be the root element");
            } else {
            //根据元素名进行解析
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                //递归调用进行解析,也就是深度优先遍历
                rInflateChildren(parser, view, attrs, true);
                //将解析到的View添加到viewGroup里面,也就是他的parent
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }
  • rInflate方法进行深度优先遍历来解析视图树,完了之后,整颗视图树就构建完毕,当调用了Activity的onResume之后,我们通过setContentView设置的内容就会出现在我们的视野

运用单例模式

  • 在Android应用开发中,ImageLoader是我们最常用的开发工具库之一,android中最著名的ImageLoader就是Android-Universal-Image-Loader
  • 他的一般使用过程是
public void initImageLoader(Context context){
        //使用Builder构建ImageLoader的配置对象
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(context)
                //设置加载图片的线程数
                .threadPriority(Thread.NORM_PRIORITY - 2 )
                //解码图像的大尺寸,将在内存中缓存先前解码图像的小尺寸
                .denyCacheImageMultipleSizesInMemory()
                //设置磁盘缓存文件名称
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                //设置加载显示图片队列进程
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs()
                .build();
        //使用配置对象初始化ImageLoader
        ImageLoader.getInstance().init(configuration);
        //加载图片
        ImageLoader.getInstance().displayImage("图片url",mImageView);
    }

总结

  • 单例模式的优缺点
优点 缺点
单例模式只有一个实例,减少了内存开支,特别是一个对象需要频繁的创建销毁时,而且创建或销毁时性能又无法优化名,单例模式的有点就非常明显 单例模式一般没有接口,扩展很困难,若要扩展,除了修改代码基本上没别的途径
由于只生成一个实例,所以,减少了系统的性能开销,当一个对象的产生需要比较多的资源时,则可以通过在应用启动时直接产生一个单例对象,然后用永久驻留内存的方式来解决 单例对象如果持有Context,那么很容易引发内存泄漏,此时需要注意传递给单例对象的Context最好是Application Context
单例模式可以避免对资源的多重占用,例如只有一个实例存在内存中,避免对同年哥一个资源文件的同时写操作
单例模式可以在系统设置全局的访问点,优化和共享资源访问,例如:可以设计一个单例类,负责所有数据表的映射处理

猜你喜欢

转载自blog.csdn.net/asffghfgfghfg1556/article/details/81544897
今日推荐