美文网首页
Builder模式变种

Builder模式变种

作者: kinglong1984 | 来源:发表于2018-09-30 09:52 被阅读1次

    Builder模式的简化

    1.省略Director角色,Builder定义在Product内,ConcreteBuilder定义在Product子类中。

    2.省略抽象Builder角色,只剩下ConcreteBuilder和Product两个角色。

       具体做法是在Procuct中定义内部类Builder并提供具体的实现。

    Android中的应用

    1.Android中的AlertDialog.Builder

    AlertDialog.Builder builder=newAlertDialog.Builder(context);

    builder.setIcon(R.drawable.icon).setTitle("标题") .setMessage("消息").setPositiveButton("取消",newDialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog,int which){//todo} }).setNegativeButton("确定",newDialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog,int which){//todo} });

    builder.create().show();

    2.OkHttp中OkHttpClient的创建

    Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();

    3.Retrofit中Retrofit对象的创建

    Retrofit retrofit =newRetrofit.Builder() .client(createOkHttp()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(BASE_URL) .build();

    示例代码

    public class Product {

        private String name;   

        private int size;    

        private Product(Builder builder){

            this.name=builder.name;

            this.size=builder.size;

        }

        public String getName() {return name; }

        public void setName(String name) {this.name = name; }

        public int getSize() {return size; }

        public void setSize(int size) {this.size= size; }

        static class Builder{

            private String name;

            private int size;

            public Builder setName(String name) {

                this.name=name;

                return this;

           }

            public Builder setSize(int size) {

                this.size=size;

                return this;

            }

            public Product build(){

                return new Product(this);

            }

        }

    }

    创建Product的示例:

    Product productA= new Product.Builder()

          .setName("产品A")

          .setSize(100)

          .build();

    Product productB= new Product.Builder()

          .setSize(200)

          .setName("产品B")

          .build();

    相关文章

      网友评论

          本文标题:Builder模式变种

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