How to ensure that builder pattern is completed?

后端 未结 7 1681
鱼传尺愫
鱼传尺愫 2021-02-05 13:38

EDIT: I am not worried about being called in the wrong order since this is enforced through using multiple interfaces, I am just worried about the terminal method getting called

7条回答
  •  一向
    一向 (楼主)
    2021-02-05 14:25

    public class MyClass {
        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 MyClass(Builder builder) {
            first = builder.first;
            second = builder.second;
            third = builder.third;
        }
    
        public static void test() {
            // Compile Error!
            MyClass c1 = new MyClass(MyClass.Builder.create().setFirst("1").setSecond("2"));
    
            // Compile Error!
            MyClass c2 = new MyClass(MyClass.Builder.create().setFirst("1").setThird("3"));
    
            // Works!, all params supplied.
            MyClass c3 = new MyClass(MyClass.Builder.create().setFirst("1").setSecond("2").setThird("3"));
        }
    }
    

提交回复
热议问题