DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Forms With Camunda and Spring StateMachine
  • Understanding AVL Trees in C#: A Guide to Self-Balancing Binary Search Trees
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!

Trending

  • AI Agents: A New Era for Integration Professionals
  • Implementing Explainable AI in CRM Using Stream Processing
  • How to Introduce a New API Quickly Using Micronaut
  • Useful System Table Queries in Relational Databases
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Implementing NestedBuilder

Implementing NestedBuilder

If you're working with the Builder Pattern, you might find your relations growing complex. The NestedBuilder class lets proxies serve as parents and children at the same time.

By 
Sven Ruppert user avatar
Sven Ruppert
DZone Core CORE ·
Updated Dec. 16, 16 · Tutorial
Likes (20)
Comment
Save
Tweet
Share
51.2K Views

Join the DZone community and get the full member experience.

Join For Free

While working with the Builder Pattern, you will come to the point when you have to build up complex objects. Suppose we would like to create "Car." It consists of attributes like engine, machine, and a number of wheels. For this purpose, we use the following class model.

public class Car {
    private Engine engine;
    private List<Wheel> wheelList;
}

public class Engine {
    private int power;
    private int type;
}

public class Wheel {
    private int size;
    private int type;
    private int colour;
}


Now it is possible to generate a corresponding Builder for each class. If you adhere to the basic pattern it will look like this for the class Wheel:

public static final class Builder {
     private int size;
     private int type;
     private int colour;

     private Builder() {}

     public Builder withSize(int size) {
         this.size = size;
         return this;
     }

     public Builder withType(int type) {
         this.type = type;
         return this;
     }

     public Builder withColour(int colour) {
         this.colour = colour;
         return this;
     }

     public Wheel build() {
         return new Wheel(this);
     }
 }


The Builder is implemented as an inner static class and, thus, it makes modifications in the class Wheel, which allows one to use only the Builder to create an instance. Of course, here I have omitted the option via reflection.

public class Wheel {

    private int size;
    private int type;
    private int colour;

    private Wheel(Builder builder) {
        setSize(builder.size);
        setType(builder.type);
        setColour(builder.colour);
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static Builder newBuilder(Wheel copy) {
        Builder builder = new Builder();
        builder.size = copy.size;
        builder.type = copy.type;
        builder.colour = copy.colour;
        return builder;
    }
...}


But what does it look like if we want to create an instance of the class Car? Here we come to the point when we have to add the instance of the class Wheel to the instance of the class Car.

public class Main {
  public static void main(String[] args) {

    Engine engine = Engine.newBuilder().withPower(100).withType(5).build();

    Wheel wheel1 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel2 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel3 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();

    List<Wheel> wheels = new ArrayList<>();
    wheels.add(wheel1);
    wheels.add(wheel2);
    wheels.add(wheel3);

    Car car = Car.newBuilder()
                 .withEngine(engine)
                 .withWheelList(wheels)
                 .build();

    System.out.println("car = " + car);
  }
}


This source code is not particularly well-done and in no way compact. So how can one adjust the Builder Pattern in order to manually write as little of the Builder source code as possible and to have more convenience when using it? WheelListBuilder Let's take a small detour. For example, to ensure, that only four wheels can be added to Car, you can create a WheelListBuilder. Here you can check in the method build() if four instances of the class Wheel are available.

public class WheelListBuilder {

    public static WheelListBuilder newBuilder(){
      return new WheelListBuilder();
    }

    private WheelListBuilder() {}

    private List<Wheel> wheelList;

    public WheelListBuilder withNewList(){
        this.wheelList = new ArrayList<>();
        return this;
    }
    public WheelListBuilder withList(List wheelList){
        this.wheelList = wheelList;
        return this;
    }

    public WheelListBuilder addWheel(Wheel wheel){
        this.wheelList.add(wheel);
        return this;
    }

    public List<Wheel> build(){
        //test if there are 4 instances....
        return this.wheelList;
    }

}


Now our example is as follows:

public class Main {
  public static void main(String[] args) {

    Engine engine = Engine.newBuilder().withPower(100).withType(5).build();

    Wheel wheel1 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel2 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();
    Wheel wheel3 = Wheel.newBuilder().withType(2).withColour(3).withSize(4).build();

//        List<Wheel> wheels = new ArrayList<>();
//        wheels.add(wheel1);
//        wheels.add(wheel2);
//        wheels.add(wheel3);

    List<Wheel> wheelList = WheelListBuilder.newBuilder()
        .withNewList()
        .addWheel(wheel1)
        .addWheel(wheel2)
        .addWheel(wheel3)
        .build();//more robust if you add tests at build()

    Car car = Car.newBuilder()
        .withEngine(engine)
        .withWheelList(wheelList)
        .build();

    System.out.println("car = " + car);
  }
}


The next step is to connect the Builder of the class Wheel to the class WheelListBuilder. The aim of it is to get a Fluent API — in order to avoid individual creation of each instance of the class Wheel and its connection via the method addWheel(Wheel w) to the WheelListBuilder. For programmers, it should look like this:

List<Wheel> wheels = wheelListBuilder
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .build();


The following thing happens here: As soon as the method addWheel() is called, a new instance of the class WheelBuilder should be returned. The method addWheelToList() creates the instance of the class Wheel and adds it to the list. To achieve it, one has to modify both Builders involved. On the side of the WheelBuilder, the method addWheelToList() is added. This method adds the instance of the class Wheel to the WheelListBuilder and returns the instance of the class WheelListBuilder.

private WheelListBuilder wheelListBuilder;

public WheelListBuilder addWheelToList(){
  this.wheelListBuilder.addWheel(this.build());
  return this.wheelListBuilder;
}


On the side of the class WheelListBuilder, only the method addWheel() is added.

public Wheel.Builder addWheel() {
  Wheel.Builder builder = Wheel.newBuilder();
  builder.withWheelListBuilder(this);
  return builder;
}


If we apply this to the other Builder, we will get a quite considerable result:

Car car = Car.newBuilder()
    .addEngine().withPower(100).withType(5).done()
    .addWheels()
      .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
      .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
      .addWheel().withType(1).withSize(2).withColour(2).addWheelToList()
    .done()
    .build();


NestedBuilder

Up to now, the Builders were modified manually. It can be easily implemented in a generic way, i.e. in the form of a Builder tree. Thus, each Builder knows its Children and its Parent. The necessary implementation can be found in the class NestedBuilder. It is assumed here that the methods for setting attributes always begin with "with". Since it is true for the most Builder Generators, no manual adjustment is necessary.

public abstract class NestedBuilder<T, V> {
  /**
   * To get the parent builder
   *
   * @return T the instance of the parent builder
   */
  public T done() {
    Class<?> parentClass = parent.getClass();
    try {
      V build = this.build();
      String methodname = "with" + build.getClass().getSimpleName();
      Method method = parentClass.getDeclaredMethod(methodname, build.getClass());
      method.invoke(parent, build);
    } catch (NoSuchMethodException
            | IllegalAccessException
            | InvocationTargetException e) {
      e.printStackTrace();
    }
    return parent;
  }

  public abstract V build();

  protected T parent;

  /**
   * @param parent
   * @return
   */
  public <P extends NestedBuilder<T, V>> P withParentBuilder(T parent) {
    this.parent = parent;
    return (P) this;
  }
}


Now we can add to one Parent the specific methods for connecting to the Children. A derivation from NestedBuilder is not needed.

public class Parent {

  private KidA kidA;
  private KidB kidB;

  //snipp.....

  public static final class Builder {
    private KidA kidA;
    private KidB kidB;

    private Builder() {
    }

    public Builder withKidA(KidA kidA) {
      this.kidA = kidA;
      return this;
    }

    public Builder withKidB(KidB kidB) {
      this.kidB = kidB;
      return this;
    }

    // to add manually
    private KidA.Builder builderKidA = KidA.newBuilder().withParentBuilder(this);
    private KidB.Builder builderKidB = KidB.newBuilder().withParentBuilder(this);

    public KidA.Builder addKidA() {
      return this.builderKidA;
    }

    public KidB.Builder addKidB() {
      return this.builderKidB;
    }
    //---------

    public Parent build() {
      return new Parent(this);
    }
  }
}


And on the Children side, it is as follows: Here it must be derived only from NestedBuilder:

public class KidA {

  private String note;

  @Override
  public String toString() {
    return "KidA{" +
        "note='" + note + '\'' +
        '}';
  }

  private KidA(Builder builder) {
    note = builder.note;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public static final class Builder extends NestedBuilder<Parent.Builder, KidA> {
    private String note;

    private Builder() {
    }

    public Builder withNote(String note) {
      this.note = note;
      return this;
    }

    public KidA build() {
      return new KidA(this);
    }

  }
}


The usage is then very compact, as it is seen in the previous example.

public class Main {
  public static void main(String[] args) {
    Parent build = Parent.newBuilder()
        .addKidA().withNote("A").done()
        .addKidB().withNote("B").done()
        .build();
    System.out.println("build = " + build);
  }
}


Conclusion

Of course, any combination is possible. It means that a Proxy can be Parent and Child at the same time. So there is nothing else to prevent the building of the complex structures.

public class Main {
  public static void main(String[] args) {
    Parent build = Parent.newBuilder()
        .addKidA().withNote("A")
                  .addKidB().withNote("B").done()
        .done()
        .build();
    System.out.println("build = " + build);
  }
}


Builder pattern Attribute (computing) Programmer (hardware) Tree (data structure) Implementation Machine Form (document) Build (game engine)

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Forms With Camunda and Spring StateMachine
  • Understanding AVL Trees in C#: A Guide to Self-Balancing Binary Search Trees
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!