Android开发之Buidler模式初探结合AlertDialog.Builder解说

什么是Buidler模式呢?就是将一个复杂对象的构建与它的表示分离,使得相同的构建过程能够创建不同的表示.Builder模式是一步一步创建一个复杂的对象,它同意用户能够仅仅通过指定复杂对象的类型和内容就能够构建它们.

那么要为何使用Buidler呢?

是为了将构建复杂对象的过程和它的部件分开由于一个复杂的对象,不但有非常多大量组成部分,如AlertDialog对话框,有非常多组成部件,比方Tittle,Message,icon,PositiveButton等等,但远不止这些,怎样将这些部件装配成一个AlertDialog对话框呢,这个装配程可能也是一个非常复杂的步骤,Builder模式就是为了将部件和组装过程分开。通俗点说,就是我先分开生产好各个组件,然后交由还有一个类去组装这些组件。

怎样使用?

我们来看一下Android内部关于AlertDialog.Builder的源代码便能够知晓。

public class AlertDialog extends Dialog implements DialogInterface {
    // Controller, 接受Builder成员变量P中的各个參数
    private AlertController mAlert;  

    // 构造函数
    protected AlertDialog(Context context, int theme) {
        this(context, theme, true);
    }  

    // 4 : 构造AlertDialog
    AlertDialog(Context context, int theme, boolean createContextWrapper) {
        super(context, resolveDialogTheme(context, theme), createContextWrapper);
        mWindow.alwaysReadCloseOnTouchAttr();
        mAlert = new AlertController(getContext(), this, getWindow());
    }  

    // 实际上调用的是mAlert的setTitle方法
    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        mAlert.setTitle(title);
    }  

    // 实际上调用的是mAlert的setCustomTitle方法
    public void setCustomTitle(View customTitleView) {
        mAlert.setCustomTitle(customTitleView);
    }  

    public void setMessage(CharSequence message) {
        mAlert.setMessage(message);
    }  

    // AlertDialog其它的代码省略  

    // ************  Builder为AlertDialog的内部类   *******************
    public static class Builder {
        // 1 :该类用来存储AlertDialog的各个參数, 比如title, message, icon等.
        private final AlertController.AlertParams P;  

        /**
         * Constructor using a context for this builder and the {@link AlertDialog} it creates.
         */
        public Builder(Context context) {
            this(context, resolveDialogTheme(context, 0));
        }  

        public Builder(Context context, int theme) {
            P = new AlertController.AlertParams(new ContextThemeWrapper(
                    context, resolveDialogTheme(context, theme)));
            mTheme = theme;
        }  

        // 2:设置各种參数到P
        public Builder setTitle(CharSequence title) {
            P.mTitle = title;
            return this;
        }  

        public Builder setMessage(CharSequence message) {
            P.mMessage = message;
            return this;
        }  

        public Builder setIcon(int iconId) {
            P.mIconId = iconId;
            return this;
        }  

        public Builder setPositiveButton(CharSequence text, final OnClickListener listener) {
            P.mPositiveButtonText = text;
            P.mPositiveButtonListener = listener;
            return this;
        }  

        public Builder setView(View view) {
            P.mView = view;
            P.mViewSpacingSpecified = false;
            return this;
        }  

        // 3 : 构建AlertDialog, 传递參数
        public AlertDialog create() {
            // 调用new AlertDialog构造对象, 而且将參数传递个体AlertDialog
            final AlertDialog dialog = new AlertDialog(P.mContext, mTheme, false);
            // 5 : 将P中的參数应用的dialog中的mAlert对象中
            //这一步是核心方法我们等下看源代码继续讲
            P.apply(dialog.mAlert);
            dialog.setCancelable(P.mCancelable);
            if (P.mCancelable) {
                dialog.setCanceledOnTouchOutside(true);
            }
            dialog.setOnCancelListener(P.mOnCancelListener);
            if (P.mOnKeyListener != null) {
                dialog.setOnKeyListener(P.mOnKeyListener);
            }
            return dialog;
        }
          public AlertDialog show() {
            //6:显示dialog
            AlertDialog dialog = create();
            dialog.show();
            return dialog;
        }
    }  

}

从上面的源代码中我们能够看到,对话框的构建是通过Builder来设置AlertDialog中的title, message, button等參数, 这些參数都存储在类型为AlertController.AlertParams的成员变量P中,AlertController.AlertParams中包括了与之相应的成员变量。在调用Builder类的create函数时才创建AlertDialog, 而且将Builder成员变量P中保存的參数应用到AlertDialog的mAlert对象中,最后调用dialog.show方法显示对话框。

如今我们再来看看即P.apply(dialog.mAlert)代码段。我们看看apply函数的实现 。

public void apply(AlertController dialog) {
    if (mCustomTitleView != null) {
        dialog.setCustomTitle(mCustomTitleView);
    } else {
        if (mTitle != null) {
            dialog.setTitle(mTitle);
        }
        if (mIcon != null) {
            dialog.setIcon(mIcon);
        }
        if (mIconId >= 0) {
            dialog.setIcon(mIconId);
        }
        if (mIconAttrId > 0) {
            dialog.setIcon(dialog.getIconAttributeResId(mIconAttrId));
        }
    }
    if (mMessage != null) {
        dialog.setMessage(mMessage);
    }
    if (mPositiveButtonText != null) {
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, mPositiveButtonText,
                mPositiveButtonListener, null);
    }
    if (mNegativeButtonText != null) {
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText,
                mNegativeButtonListener, null);
    }
    if (mNeutralButtonText != null) {
        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText,
                mNeutralButtonListener, null);
    }
    if (mForceInverseBackground) {
        dialog.setInverseBackgroundForced(true);
    }
    // For a list, the client can either supply an array of items or an
    // adapter or a cursor
    if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
        createListView(dialog);
    }
    if (mView != null) {
        if (mViewSpacingSpecified) {
            dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
                    mViewSpacingBottom);
        } else {
            dialog.setView(mView);
        }
    }
}

实际上就是把P中的參数挨个的设置到AlertController中, 也就是AlertDialog中的mAlert对象。从AlertDialog的各个setter方法中我们也能够看到,实际上也都是调用了mAlert相应的setter方法。
       综上看完上面源代码之后我们就能够发现,怪不得我们平时调用对话框的时候能够直接使用,AlertDialog dialog = new AlertDialog(P.mContext, mTheme, false);不用Alert.Builder方法创建也能够,由于其本质是一样的,Builder仅仅是把组件的生产过程化成一步步实行而已。

这样做有什么实际作用呢?

在Java实际使用中,我们经经常使用到"池"(Pool)的概念,当资源提供者无法提供足够的资源,而且这些资源须要被非常多用户重复共享时,就须要使用池。"池"实际是一段内存,当池中有一些复杂的资源的"断肢"(比方数据库的连接池,或许有时一个连接会中断),假设循环再利用这些"断肢",将提高内存使用效率,提高池的性能,而在这里AlertDialog.builder就是这个池,改动Builder模式中p.apply(组装)类使之能诊断"断肢"断在哪个部件上,再修复这个部件.

时间: 2024-07-29 16:56:35

Android开发之Buidler模式初探结合AlertDialog.Builder解说的相关文章

Android开发之Buidler模式初探结合AlertDialog.Builder讲解

什么是Buidler模式呢?就是将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.Builder模式是一步一步创建一个复杂的对象,它允许用户可以只通过指定复杂对象的类型和内容就可以构建它们. 那么要为何使用Buidler呢? 是为了将构建复杂对象的过程和它的部件分开因为一个复杂的对象,不但有很多大量组成部分,如AlertDialog对话框,有很多组成部件,比如Tittle,Message,icon,PositiveButton等等,但远不止这些,如何将这些部件装配成一个A

Android开发之MVP模式的使用

前几天发现,在Android项目代码里有一个Activity类行数居然有1000多行,而600行左右都是逻辑控制,真正和页面控件处理相关的代码不多,虽然可以用#region <>...#endregion块包起来,但是整体来说,页面和逻辑处理揉得太紧密了,有时代码复用起来也不方便,于是,决定重构,找了一下,有MVP(Model-View-Presenter,Model层负责数据管理,View层负责页面控件数据展示与设置,Presenter负责逻辑处理,控制View层如何显示与展示数据,这种层次

Android开发之assets目录下资源使用总结

预前知识: Android资源文件分类: Android资源文件大致可以分为两种: 第一种是res目录下存放的可编译的资源文件: 这种资源文件系统会在R.java里面自动生成该资源文件的ID,所以访问这种资源文件比较简单,通过R.XXX.ID即可: 第二种是assets目录下存放的原生资源文件: 因为系统在编译的时候不会编译assets下的资源文件,所以我们不能通过R.XXX.ID的方式访问它们.那我么能不能通过该资源的绝对路径去访问它们呢?因为apk安装之后会放在/data/app/**.ap

Android开发之WebView详解

概述: 一个显示网页的视图.这个类是你可以滚动自己的Web浏览器或在你的Activity中简单地显示一些在线内容的基础.它使用了WebKit渲染引擎来显示网页,包括向前和向后导航的方法(通过历史记录),放大和缩小,执行文本搜索等. 需要注意的是:为了让你的应用能够使用WebView访问互联网和加载网页,你必须添加Internet的权限在Android Manifest文件中: <uses-permission android:name="android.permission.INTERNE

Android开发之AudioManager(音频管理器)详解

AudioManager简介: AudioManager类提供了访问音量和振铃器mode控制.使用Context.getSystemService(Context.AUDIO_SERVICE)来得到这个类的一个实例. 公有方法: Public Methods int abandonAudioFocus(AudioManager.OnAudioFocusChangeListenerl) 放弃音频的焦点. void adjustStreamVolume(int streamType, int dir

android开发之Intent.setFlags()_让Android点击通知栏信息后返回正在运行的程序

android开发之Intent.setFlags()_让Android点击通知栏信息后返回正在运行的程序 在应用里使用了后台服务,并且在通知栏推送了消息,希望点击这个消息回到activity, 结果总是存在好几个同样的activity,就算要返回的activity正在前台,点击消息后也会重新打开一个一样的activity,返回好几次才能退出, 而不能像qq之类的点击通知栏消息回到之前存在的activity,如果存在就不再新建一个activity 说的有点绕,如果是遇到此类问题的肯定能懂,没遇到

Android开发之PopupWindow

/* *  Android开发之PopupWindow * *  Created on: 2011-8-8 *  Author: blueeagle *  Email: [email protected] */ 聪明的人善于总结,记录,不知道这是谁说的了,反正要当一个聪明人,我得先学会总结,记录.最近在Android的学习过程中,发现 PopupWindow也是值得研究一番的一个东东,因此拿过来说道说道.与其相似的就归纳到一起说道吧,那就是AlertDialog和Toast. PopupWind

Android开发之Sensors与摇一摇

Sensor概述 基于Android的设备有内置的传感器,测量运动,方向,和各种环境条件.这些传感器能够提供原始数据的高精度和准确度,并且是有用的如果你想要监测装置.定位的三维运动,或者你想监控在设备周围环境的变化.例如,一个可能的轨道的读数装置的重力传感器来推断用户的手势和身体的动作复杂,如倾斜.摇晃.旋转.摆动或.同样,一个天气应用程序可能使用的设备的温度传感器和湿度传感器来计算和报告. Android平台支持的传感器三大类: 运动传感器 这些传感器测量加速度的力和旋转力沿三轴.这一类包括加

Android开发之”再按一次退出程序“的实现

现在移动客户端退出程序对话框退出越来越不流行了,都开始使用连续按两次来退出,即著名的“再按一次退出程序”模式.现在就看看怎么实现的吧. @SuppressLint("HandlerLeak") Handler handler = new Handler(){ public void handleMessage(Message msg){ switch (msg.what) { } } }; boolean willExit = false; @Override public void