use Builder pattern from the constructor in a subclass

后端 未结 2 1215
死守一世寂寞
死守一世寂寞 2021-01-03 02:17

I am currently using the Builder pattern, following closely the Java implementation suggested in the Wikipedia article Builder pattern http://en.wikipedia.org/wiki/

2条回答
  •  耶瑟儿~
    2021-01-03 02:18

    You might want to consider having a nested MySophisticatedObject.Builder which extends MyPrimitiveObject.Builder, and overrides its build() method. Have a protected constructor in the builder to accept the instance on which to set values:

    public class MyPrimitiveObject {
      private String identifier="unknown";
      public static class Builder {
        private final MyPrimitiveObject obj;
        public MyPrimitiveObject build() { return obj; }
        public Builder setidentifier (String val) {
         obj.identifier = val;
         return this;
        }
    
        public Builder() {
            this(new MyPrimitiveObject());
        }
    
        public Builder(MyPrimitiveObject obj) {
            this.obj = obj;
        }
      }
      ...
    }
    
    public class MySophisticatedObject extends MyPrimitiveObject {
      private String description;
    
      public static class Builder extends MyPrimitiveObject.Builder {
        private final MySophisticatedObject obj;
        public Builder() {
          this(new MySophisticatedObject());
          super.setIdentifier(generateUUID());
        }     
        public Builder(MySophisticatedObject obj) {
          super(obj);
          this.obj = obj;
        }
    
        public MySophisticatedObject build() {
          return obj;
        }
    
        // Add code to set the description etc.
      }
    }
    

提交回复
热议问题