android中builder模式的使用

变种的Builder模式的自动化生产实现:


 

AS安装插件  Innerbuilde


新建User类

public class User {
    private final String name; //必选
    private final String age;
    private final String phone;
    private final String dec;
}

右键-->Generate-->Builder生产,然后稍作修改即可

package com.loaderman.example;



public class User {
    private final String name;
    private final String age;
    private final String phone;
    private final String dec;

    private User(Builder builder) {
        name = builder.name; //必选
        age = builder.age;
        phone = builder.phone;
        dec = builder.dec;
    }

    public static final class Builder {
        private final String name;//必选
        private String age;
        private String phone;
        private String dec;
        public Builder(String name) {
            this.name=name;
        }
        public Builder age(String val) {
            age = val;
            return this;
        }
        public Builder phone(String val) {
            phone = val;
            return this;
        }
        public Builder dec(String val) {
            dec = val;
            return this;
        }
        public User build() {
            return new User(this);
        }
    }
}

使用:

  User user = new User
                .Builder("哈哈")
                .age("12")
                .dec("描述")
                .build();

 

posted on 2018-11-16 17:20  LoaderMan  阅读(871)  评论(0编辑  收藏  举报

导航