在Builder模式中,通常需要至少为所有必需的属性提供值,否则无法构建对象。以下是解决方法的示例:
public class User {
    private final String name;
    private final String email;
    private final int age;
    private final String address;
  
    private User(UserBuilder builder) {
        this.name = builder.name;
        this.email = builder.email;
        this.age = builder.age;
        this.address = builder.address;
    }
  
    public static class UserBuilder {
        private final String name;
        private final String email;
        private int age;
        private String address;
        
        // 必填属性构造函数
        public UserBuilder(String name, String email) {
            this.name = name;
            this.email = email;
        }
        
        // 可选属性setter方法
        public UserBuilder age(int age) {
            this.age = age;
            return this;
        }
        
        public UserBuilder address(String address) {
            this.address = address;
            return this;
        }
        
        // 构建User对象,校验必须属性是否已赋值
        public User build() {
            if (name == null || email == null) {
                throw new IllegalStateException("必需属性未设置");
            }
            return new User(this);
        }
    }
}
通过利用Builder模式,我们可以实现以下优点: