What is Fluent Builder ?
A fluent builder is a design pattern in Java that allows us to create complex objects with a more readable and expressive syntax.
Uses of Fluent Builder:
It is often used to chain method calls together to configure and build an object. The key idea behind the fluent builder pattern is to return the builder itself from each method call, allowing us to chain method calls together in a fluent and intuitive way.
Example : we have a “pizza” class and there are various attributes of it. so there we will use the fluent builder pattern.
Java
public class Pizza { private String size; private boolean cheese; private boolean pepperoni; private boolean mushrooms; private Pizza() { // Private constructor to force the use of the builder } public static class PizzaBuilder { private Pizza pizza; public PizzaBuilder() { pizza = new Pizza(); } public PizzaBuilder withSize(String size) { pizza.size = size; return this ; } public PizzaBuilder withCheese( boolean cheese) { pizza.cheese = cheese; return this ; } public PizzaBuilder withPepperoni( boolean pepperoni) { pizza.pepperoni = pepperoni; return this ; } public PizzaBuilder withMushrooms( boolean mushrooms) { pizza.mushrooms = mushrooms; return this ; } public Pizza build() { return pizza; } } @Override public String toString() { return "Pizza{" + "size='" + size + '\ '' + ", cheese=" + cheese + ", pepperoni=" + pepperoni + ", mushrooms=" + mushrooms + '}' ; } public static void main(String[] args) { Pizza pizza = new PizzaBuilder() .withSize( "Large" ) .withCheese( true ) .withPepperoni( true ) .withMushrooms( true ) .build(); System.out.println(pizza); } } |
Pizza{size='Large', cheese=true, pepperoni=true, mushrooms=true}
Explanation of example :
In this example, we have a Pizza class with a nested PizzaBuilder class. The Pizza class has private fields for pizza properties like size, cheese, pepperoni, and mushrooms. The PizzaBuilder class provides methods to set these properties and then returns the built Pizza object. This allows us to create a Pizza object using a fluent and readable syntax.
Note: In the main method, we demonstrate how to use the Fluent Builder Pattern to create a Pizza object with various properties.
Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java
Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly useful when dealing with a complex object with many optional parameters or configurations.
Important Topics for Builder Design Pattern in Java
- Use Cases of the Builder Pattern in Java
- Example for Builder Method in Java:
- What is Fluent Builder ?
- What is Faceted Builder?