美文网首页
遇到多个构造器参数时要考虑用构建器

遇到多个构造器参数时要考虑用构建器

作者: Draymond_er | 来源:发表于2018-09-27 11:11 被阅读0次
    /**
     * Created by chengkang
     * 2018/9/19 下午4:03
     */
    public class User {
        private final String name;//required
        private final int year;//optional
        private final int sexNum;//optional
        private final String job;//optional
    
        public static class Builder{
            private final String name;//required
    
            private int year = 0;//optional
            private int sexNum = 0;//optional
            private String job = "";//optional
            public Builder(String name){
                this.name = name;
            }
            public Builder year(int val){
                year = val;
                return this;
            }
            public Builder sexNum(int val){
                sexNum = val;
                return this;
            }
            public Builder job(String val){
                job = val;
                return this;
            }
    
            public User build(){
                return new User(this);
            }
        }
        private User(Builder builder){
            name = builder.name;
            year = builder.year;
            job = builder.job;
            sexNum = builder.sexNum;
        }
    
        public static void main(String[] args) {
            User user = new Builder("ck").year(24).sexNum(1).job("IT").build();
            System.out.println(user.name);
            System.out.println(user.year);
            System.out.println(user.sexNum);
            System.out.println(user.job);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:遇到多个构造器参数时要考虑用构建器

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