In java, can you use the builder pattern with required and reassignable fields?

后端 未结 5 780
南笙
南笙 2021-01-20 01:57

This is related to the following question:

How to improve the builder pattern?

I\'m curious whether it\'s possible to implement a builder with the following

5条回答
  •  没有蜡笔的小新
    2021-01-20 02:05

    Your requirements are really hard, but see if this generic solution fits the bill:

    public final class Foo {
    
        public final int a;
        public final int b;
        public final int c;
    
        private Foo(
                int a,
                int b,
                int c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }
    
        public static BuilderA> newBuilder() {
            return new BuilderFinal();
        }
    
        public static class BuilderA> {
            private volatile int a;
    
            @SuppressWarnings("unchecked")
            public T a(int v) {
                a = v;
                return (T) this;
            }
    
            public int a() {
                return a;
            }
        }
    
        public static class BuilderB> extends BuilderA {
            private volatile int b;
    
            @SuppressWarnings("unchecked")
            public T b(int v) {
                b = v;
                return (T) this;
            }
    
            public int b() {
                return b;
            }
        }
    
        public static class BuilderC extends BuilderB {
            private volatile int c;
    
            @SuppressWarnings("unchecked")
            public T c(int v) {
                c = v;
                return (T) this;
            }
    
            public int c() {
                return c;
            }
        }
    
        public static class BuilderFinal extends BuilderC {
    
            public Foo build() {
                return new Foo(
                        a(),
                        b(),
                        c());
            }
        }
    
        public static void main(String[] args) {
            Foo f1 = newBuilder().a(1).b(2).c(3).build();
            Foo f2 = newBuilder().a(1).b(2).c(3).a(4).build();
        }
    
    }
    

提交回复
热议问题