How to improve the builder pattern?

后端 未结 10 911
野性不改
野性不改 2020-12-02 10:34

Motivation

Recently I searched for a way to initialize a complex object without passing a lot of parameter to the constructor. I tried it with the builder pattern,

10条回答
  •  醉话见心
    2020-12-02 11:08

    public class Complex {
        private final String first;
        private final String second;
        private final String third;
    
        public static class False {}
        public static class True {}
    
        public static class Builder {
            private String first;
            private String second;
            private String third;
    
            private Builder() {}
    
            public static Builder create() {
                return new Builder<>();
            }
    
            public Builder setFirst(String first) {
                this.first = first;
                return (Builder)this;
            }
    
            public Builder setSecond(String second) {
                this.second = second;
                return (Builder)this;
            }
    
            public Builder setThird(String third) {
                this.third = third;
                return (Builder)this;
            }
        }
    
        public Complex(Builder builder) {
            first = builder.first;
            second = builder.second;
            third = builder.third;
        }
    
        public static void test() {
            // Compile Error!
            Complex c1 = new Complex(Complex.Builder.create().setFirst("1").setSecond("2"));
    
            // Compile Error!
            Complex c2 = new Complex(Complex.Builder.create().setFirst("1").setThird("3"));
    
            // Works!, all params supplied.
            Complex c3 = new Complex(Complex.Builder.create().setFirst("1").setSecond("2").setThird("3"));
        }
    }
    

提交回复
热议问题