How to write builder pattern using java 8 lambda or lombok

1.9k Views Asked by At

I have pojo classes as shown below.

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

I am using Below pojo classes as parameters in "Car" pojo class.

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

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

Can you please help how to write builder pattern using java 8 lambda or lombok.

1

There are 1 best solutions below

0
On

The builder patten is often used to construct objects with many properties. It makes it easier to read initialisations by having parameters named at the callsite, while helping you only allow the construction of valid objects.

Builder implementations tend to either rely on the constructed object being mutable, and setting fields as you go, or on duplicating all the settable fields within the builder.

Since Java 8, I find myself frequently creating lightweight builders by defining an interface for each initialisation stage.

you should definitely read this -

http://benjiweber.co.uk/blog/2014/11/02/builder-pattern-with-java-8-lambdas/