欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

随手记之建造者模式

程序员文章站 2022-06-04 17:01:49
...

1 :直接上代码

public class User {
    private String name;
    private boolean sex;
    private  int age;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                '}';
    }

    private User(Builder builder) {
       this.name = builder.name;
        this.sex = builder.sex;
        this.age = builder.age;
    }


    public static class Builder {
        private String name;
        private boolean sex;
        private  int age;

         /**
         * //如果有参数是必须要有的,可以这样写
         * public Builder(String name){
         * this.name = name;
         * }
         */

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

        public Builder setSex(boolean sex) {
            this.sex = sex;
            return this;
        }

        public Builder setAge(int age) {
            this.age = age;
            return this;
        }

        public User create(){
            return new User(this);
        }
    }
}

2 :test

  public static void main(String[] args){
       User user = new User.Builder()
               .setAge(1)
               .setName("practicing")
               .setSex(true)
               .create();
       System.out.print(user.toString());
    }

3 :输出

User{name='practicing', sex=true, age=1}
相关标签: builder