美文网首页工作生活
android 源码设计模式读书笔记(三)Builder模式

android 源码设计模式读书笔记(三)Builder模式

作者: 刘景昌 | 来源:发表于2019-07-02 12:39 被阅读0次

定义:讲一个复杂对象的构建与它的表示分离,使同样的构建构建过程可以创建不同的表达形式
使用场景:
(1)相同的方法不同的执行顺序,产生不同的事件结果时
(2)多个部件或零件,都可以装配到到一个对象中,但是产生的结果有不想同时
(3)产品非常的复杂,或者展品类中的调用顺序不同产生不同的作用,这个时候使用建造者只非常合适的
(4) 当初始化一个对象特别复杂。如参数特别多,且很多参数具有默认值的时候
我们都知道在android里面AlertDialog使用的就是建造者模式,虽然很少使用这个类了 但是我们可以尝试的仿造一下 并且我们做好养成一个好习惯 最写程序之间 画出自己的Uml 在根据Uml去实现整个代码。
我们根据AlerDialog的结构仿出自定义dialog的uml图


image.png

下面我们要做的就是把这个Uml转换成一个我们用建造模式实现的dialog

实现代码

public class CustomDialog extends Dialog {
    //持有Builder
    private static DialogBuilder builder;

    private static class DialogParams {
        private Context context;
        //标题
        private String title;
    }

    public static class DialogBuilder {
        //持有Product对象
        private DialogParams p;

        DialogBuilder(Context context) {
            p = new DialogParams();
            p.context = context;
        }

        public DialogBuilder title(String text) {
            p.title = text;
            return builder;
        }

        void clear() {
            p = null;
        }

        public CustomDialog create() {
            return new CustomDialog(p);
        }

        //按钮点击回调
        public interface ButtonClickLister {
            void onClick(CustomDialog dialog);
        }
    }


    public static DialogBuilder with(Context context) {
        if (builder == null) {
            builder = new DialogBuilder(context);
        }
        return builder;
    }
    private CustomDialog(DialogParams p) {
        //设置没有标题的Dialog风格
        super(p.context, R.style.my_dialog);
        setContentView(R.layout.dialog_custom);
        TextView title = findViewById(R.id.title_textview_canceldialog);
        title.setText(p.title);
    }
}

调用

   CustomDialog.with(this).title("我是个逗逼").create().show();

这是是自己实现的一个一个建造的demo 顺便学着画类图 向往可以给大家带去更好的思路。

相关文章

网友评论

    本文标题:android 源码设计模式读书笔记(三)Builder模式

    本文链接:https://www.haomeiwen.com/subject/guwwcctx.html