Builder pattern for polymorphic object hierarchy: possible with Java?

后端 未结 6 882
谎友^
谎友^ 2020-12-08 01:11

I have a hierarchy of interfaces, with Child implementing Parent. I would like to work with immutable objects, so I would like to design Bui

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 01:44

    maybe like this without builders?:

    interface P {
        public Long getParentProperty();
    }
    interface C1 extends P {
        public Integer getChild1Property();
    }
    interface C2 extends P {
        public String getChild2PropertyA();
        public Object getChild2PropertyB();
    }
    abstract class PABC implements P {
        @Override public final Long getParentProperty() {
            return parentLong;
        }
        protected Long parentLong;
        protected PABC setParentProperty(Long value) {
            parentLong = value;
            return this;
        }
    }
    final class C1Impl extends PABC implements C1 {
        protected C1Impl setParentProperty(Long value) {
            super.setParentProperty(value);
            return this;
        }
        @Override public Integer getChild1Property() {
            return n;
        }
        public C1Impl setChild1Property(Integer value) {
            n = value;
            return this;
        }
        private Integer n;
    }
    final class C2Impl extends PABC implements C2 {
        private String string;
        private Object object;
    
        protected C2Impl setParentProperty(Long value) {
            super.setParentProperty(value);
            return this;
        }
        @Override public String getChild2PropertyA() {
        return string;
        }
    
        @Override public Object getChild2PropertyB() {
            return object;
        }
        C2Impl setChild2PropertyA(String string) {
            this.string=string;
            return this;
        }
        C2Impl setChild2PropertyB(Object o) {
            this.object=o;
            return this;
        }
    }
    public class Myso9138027 {
        public static void main(String[] args) {
            C1Impl c1 = new C1Impl().setChild1Property(5).setParentProperty(10L);
            C2Impl c2 = new C2Impl().setChild2PropertyA("Hello").setParentProperty(10L).setChild2PropertyB(new Object());
        }
    }
    

提交回复
热议问题