Builder Pattern and Inheritance

后端 未结 8 495
攒了一身酷
攒了一身酷 2020-11-29 19:01

I have an object hierarchy that increases in complexity as the inheritance tree deepens. None of these are abstract, hence, all of their instances serve a, more or less soph

8条回答
  •  离开以前
    2020-11-29 19:36

    The most easy fix would be to simply override the setter methods of the parent class.

    You avoid generics, it's easy to use, extend and to understand and you also avoid code duplication when calling super.setter.

    public class Lop extends Rabbit {
    
        public final float earLength;
        public final String furColour;
    
        public Lop(final LopBuilder builder) {
            super(builder);
            this.earLength = builder.earLength;
            this.furColour = builder.furColour;
        }
    
        public static class LopBuilder extends Rabbit.Builder {
    
            protected float earLength;
            protected String furColour;
    
            public LopBuilder() {}
    
            @Override
            public LopBuilder sex(final String sex) {
                super.sex(sex);
                return this;
            }
    
            @Override
            public LopBuilder name(final String name) {
                super.name(name);
                return this;
            }
    
            public LopBuilder earLength(final float length) {
                this.earLength = length;
                return this;
            }
    
            public LopBuilder furColour(final String colour) {
                this.furColour = colour;
                return this;
            }
    
            @Override
            public Lop build() {
                return new Lop(this);
            }
        }
    }
    

提交回复
热议问题