Java design pattern: Builder

Today we will take a look at another design pattern from the category of patterns for creating objects (creational patterns) – Builder.

Read more – a series of design patterns:

What is Builder design pattern?

Design pattern Builder is a software design pattern that is used to simplify the construction of complex objects by breaking it down into a set of steps.

What problem does the Builder design pattern solve?

It solves the problem of creating objects with a large number of parameters or optional properties. Instead of having constructors with a long list of parameters, design pattern Builder allows us to create objects using clear steps.

The Builder pattern works by having a separate class, called the Builder, responsible for the gradual construction of an object. This class provides methods for setting individual properties of the object. Finally, when all properties are set, we can create the actual object using the build() method.

Example of Builder implementation in Java

Now let’s see how to implement the Builder pattern in Java.

Produkt.java

In this example, we have created a class called Product that represents a product. The Product class has a private constructor and a nested Builder class that progressively sets the properties of the object.

By using the setNazov, setPopis, and setCena methods, we can set individual properties. Finally, we call the build() method, which creates an object of type Product. Then we can use the created object and access its properties.

package designpatterns;

public class Produkt {
    private String nazov;
    private String popis;
    private double cena;

    // Privatny konstruktor, aby sme zabranili priamemu vytvoreniu objektu
    private Produkt(Builder builder) {
        this.nazov = builder.nazov;
        this.popis = builder.popis;
        this.cena = builder.cena;
    }

    // Gettery pre vlastnosti objektu (nazov, popis, cena)
    public String getNazov() {
        return nazov;
    }

    public String getPopis() {
        return popis;
    }

    public double getCena() {
        return cena;
    }

    // Navrhovy vzor Builder
    public static class Builder {
        private String nazov;
        private String popis;
        private double cena;

        public Builder() {
        // Predvolene hodnoty,
        // alebo mozeme vynechat konstruktor a inicializovat hodnoty v setteroch
            this.nazov = "";
            this.popis = "";
            this.cena = 0.0;
        }

        public Builder setNazov(String nazov) {
            this.nazov = nazov;
            return this;
        }

        public Builder setPopis(String popis) {
            this.popis = popis;
            return this;
        }

        public Builder setCena(double cena) {
            this.cena = cena;
            return this;
        }

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

Here is an example of using the Product class with the Builder design pattern implemented:

Main.java

In this example, we used the Builder pattern to create an object of type Product, but this pattern is applicable to any object that has more complex property setting.

import designpatterns.Produkt;

// Pouzitie
public class Main {
    public static void main(String[] args) {
        Produkt produkt = new Produkt.Builder()
                .setNazov("Japonský čaj Gyokuro")
                .setPopis("Kvalitný tienený japonský zelený čaj")
                .setCena(29.99)
                .build();

        // Pouzitie vytvoreneho objektu produkt
        System.out.println("Názov: " + produkt.getNazov());
        System.out.println("Popis: " + produkt.getPopis());
        System.out.println("Cena: " + produkt.getCena());
    }
}
Output of the program
Output of the program

We have prepared files with the mentioned Java Builder example in the form of code that you can run directly in Java. Download the code here.

About the author

Jozef Wagner

Java Developer Senior

Viac ako 10 rokov programujem v Jave, momentálne pracujem v msg life Slovakia ako Java programátor senior a pomáham zákazníkom implementovať ich požiadavky do poistného softvéru Life Factory. Vo voľnom čase si rád oddýchnem v lese, prípadne si zahrám nejakú dobrú počítačovú hru.

Let us know about you