The Wayback Machine - https://web.archive.org/web/20240926131103/https://www.geeksforgeeks.org/builder-pattern-in-java/
Open In App

Builder Method Design Pattern in Java

Last Updated : 24 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Method Chaining: In java, Method Chaining is used to invoke multiple methods on the same object which occurs as a single statement. Method-chaining is implemented by a series of methods that return the this reference for a class instance.

Implementation: As return values of methods in a chain is this reference, this implementation allows us to invoke methods in chain by having the next method invocation on the return value of the previous method in the chain.

Java
// Java code to demonstrate method chaining

final class Student {

    // instance fields
    private int id;
    private String name;
    private String address;

    // Setter Methods
    // Note that all setters method
    // return this reference
    public Student setId(int id)
    {
        this.id = id;
        return this;
    }

    public Student setName(String name)
    {
        this.name = name;
        return this;
    }

    public Student setAddress(String address)
    {
        this.address = address;
        return this;
    }

    @Override public String toString()
    {
        return "
        id = "
        +this.id + "
        , name = "
        +this.name + "
        , address = "
        +this.address;
    }
}

// Driver class
public class MethodChainingDemo {
    public static void main(String args[])
    {
        Student student1 = new Student();
        Student student2 = new Student();

        student1.setId(1)
            .setName(" Ram & quot;)
            .setAddress(" Noida & quot;);
        student2.setId(2)
            .setName(" Shyam & quot;)
            .setAddress(" Delhi & quot;);

        System.out.println(student1);
        System.out.println(student2);
    }
}

Output:

id = 1, name = Ram, address = Noida
id = 2, name = Shyam, address = Delhi

Need of Builder Pattern: Method chaining is a useful design pattern but however if accessed concurrently, a thread may observe some fields to contain inconsistent values. Although all setter methods in above example are atomic, but calls in the method chaining can lead to inconsistent object state when the object is modified concurrently. The below example can lead us to a Student instance in an inconsistent state, for example, a student with name Ram and address Delhi. 

Output may be:

id = 2, name = Shyam, address = Noida

Another inconsistent output may be

id = 0, name = null, address = null

Note : Try running main method statements in loop(i.e. multiple requests to server simultaneously). To solve this problem, there is Builder pattern to ensure the thread-safety and atomicity of object creation. Implementation : In Builder pattern, we have a inner static class named Builder inside our Server class with instance fields for that class and also have a factory method to return an new instance of Builder class on every invocation. The setter methods will now return Builder class reference. We will also have a build method to return instances of Server side class, i.e. outer class. 

Java
// Java code to demonstrate Builder Pattern
// Server Side Code
final class Student {

    // final instance fields
    private final int id;
    private final String name;
    private final String address;

    public Student(Builder builder)
    {
        this.id = builder.id;
        this.name = builder.name;
        this.address = builder.address;
    }

    // Static class Builder
    public static class Builder {

        // instance fields
        private int id;
        private String name;
        private String address;

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

        private Builder() {}

        // Setter methods
        public Builder setId(int id)
        {
            this.id = id;
            return this;
        }
        public Builder setName(String name)
        {
            this.name = name;
            return this;
        }
        public Builder setAddress(String address)
        {
            this.address = address;
            return this;
        }

        // build method to deal with outer class
        // to return outer instance
        public Student build()
        {
            return new Student(this);
        }
    }

    @Override
    public String toString()
    {
        return "id = " + this.id + ", name = " + this.name + 
                            ", address = " + this.address;
    }
}

// Client Side Code
class StudentReceiver {

    // volatile student instance to ensure visibility
    // of shared reference to immutable objects
    private volatile Student student;

    public StudentReceiver()
    {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run()
            {
                student = Student.Builder.newInstance()
                            .setId(1)
                            .setName("Ram")
                            .setAddress("Noida")
                            .build();
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run()
            {
                student = Student.Builder.newInstance()
                            .setId(2)
                            .setName("Shyam")
                            .setAddress("Delhi")
                            .build();
            }
        });

        t1.start();
        t2.start();
        
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Student getStudent()
    {
        return student;
    }
}

// Driver class
public class BuilderDemo {
    public static void main(String args[])
    {
        StudentReceiver sr = new StudentReceiver();
        System.out.println(sr.getStudent());
    }
}

Output is guaranteed to be one of below:

id = 1, name = Ram, address = Noida

OR

id = 2, name = Shyam, address = Delhi

OR

id = 2, name = Ram, address = Noida

The Builder.newInstance() factory method can also be called with any required arguments to obtain a Builder instance by overloading it. The object of Student class is constructed with the invocation of the build() method. The above implementation of Builder pattern makes the Student class immutable and consequently thread-safe. Also note that the student field in client side code cannot be declared final because it is assigned a new immutable object. But it be declared volatile to ensure visibility of shared reference to immutable objects. Also private members of Builder class maintain encapsulation. Please have a look at append method of StringBuilder class in java.lang package to understand implementations of Builder pattern more.

Further Read: Java Design Patterns Tutorial



Previous Article
Next Article

Similar Reads

Stream.Builder accept() method in Java
Stream.Builder accept(T t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built. Syntax: void accept(T t) Parameters: This method accepts a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateException: when the builder
2 min read
Stream.Builder add() method in Java
Stream.Builder add(T t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built. Syntax: default Stream.Builder<T> add(T t) Parameters: This method adds a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateException
2 min read
IntStream.Builder add() method in Java
IntStream.Builder add(int t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built. Syntax: default IntStream.Builder add(int t) Parameters: This method accepts a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateExcep
2 min read
LongStream.Builder accept() method in Java
LongStream.Builder accept(long t) is used to insert an element into the element in the building phase of stream. It accepts an element to the stream being built. Syntax: void accept(long t) Parameters: This method accepts a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateException when
2 min read
IntStream.Builder accept() method in Java
IntStream.Builder accept(int t) is used to insert an element into the element in the building phase of stream. It accepts an element to the stream being built. Syntax: void accept(int t) Parameters: This method accepts a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateException when th
2 min read
Locale.Builder clear() method in Java with Examples
The clear() method of java.util.Locale.Builder class in Java is used to reset this Locale.Builder. It means that this method will create another instance of Locale.Builder with all the properties reset to their initial state and return it. Syntax: public Locale.Builder clear() Parameter: This method do not accept any parameter. Return Value: This m
1 min read
Locale.Builder setLanguage() method in Java with Examples
The setLanguage(String) method of java.util.Locale.Builder class in Java is used to set this Locale.Builder to the specified language. It means that this method will set the current language of Locale.Builder instance to match the provided language and return it. If the specified language is null or empty, then the language of this LocaleBuilder is
2 min read
Locale.Builder setExtension() method in Java with Examples
The setExtension() method of java.util.Locale.Builder class in Java is used to set this Locale.Builder to the specified extension key. It means that this method will set the current extension of Locale.Builder instance to match the provided extension key and value and return it. If the specified extension is null or empty, then the extension of thi
2 min read
Locale.Builder setUnicodeLocaleKeyword() method in Java with Examples
The setUnicodeLocaleKeyword() method of java.util.Locale.Builder class in Java is used to set this Locale.Builder to the specified unicodeLocaleKeyword key. It means that this method will set the current unicodeLocaleKeyword of Locale.Builder instance to match the provided unicodeLocaleKeyword key and type and return it. If the specified unicodeLoc
2 min read
Locale.Builder setLanguageTag() method in Java with Examples
The setLanguageTag(String) method of java.util.Locale.Builder class in Java is used to reset this Locale.Builder to the specified IETF BCP 47 language tag. It means that this method will reset the current state of Locale.Builder instance to match the provided language tag and return it. Syntax: public Locale.Builder setLanguageTag(String languageTa
2 min read
Locale.Builder setScript() method in Java with Examples
The setScript(String) method of java.util.Locale.Builder class in Java is used to set this Locale.Builder to the specified script. It means that this method will set the current script of Locale.Builder instance to match the provided script and return it. If the specified script is null or empty, then the script of this LocaleBuilder is removed. A
2 min read
Locale.Builder build() method in Java with Examples
The build() method of java.util.Locale.Builder class in Java is used to build a Locale from the values specified to this Locale.Builder instance. This method returns a Locale instance after building it. Syntax: public Locale build() Parameter: This method do not accept any parameter. Return Type: This method returns an Locale instance with the valu
2 min read
Locale.Builder setVariant() method in Java with Examples
The setVariant(String) method of java.util.Locale.Builder class in Java is used to set this Locale.Builder to the specified variant. It means that this method will set the current variant of Locale.Builder instance to match the provided variant and return it. If the specified variant is null or empty, then the variant of this LocaleBuilder is remov
2 min read
Locale.Builder setRegion() method in Java with Examples
The setRegion(String) method of java.util.Locale.Builder class in Java is used to set this Locale.Builder to the specified region. It means that this method will set the current region of Locale.Builder instance to match the provided region and return it. If the specified region is null or empty, then the region of this LocaleBuilder is removed. A
2 min read
Locale.Builder clearExtensions() method in Java with Examples
The clearExtensions() method of java.util.Locale.Builder class in Java is used to reset this Locale.Builder's extensions to their initial and empty state. All other values of language, scripts, variant and region remain unchanged by this method. Syntax: public Locale.Builder clearExtensions() Parameter: This method do not accept any parameter. Retu
2 min read
Locale.Builder setLocale(Locale) method in Java with Examples
The setLocale(Locale) method of java.util.Locale.Builder class in Java is used to reset this Locale.Builder to the specified Locale. It means that this method will reset the current state of Locale.Builder instance to match the provided Locale and return it. Syntax: public Locale.Builder setLocale(Locale locale) Parameter: This method accepts the l
2 min read
Stream.Builder build() in Java
Stream.Builder build() builds the stream, transitioning this builder to the built state. Syntax : Stream<T> build() Exceptions : IllegalStateException : If the builder has already transitioned to the built state, IllegalStateException is thrown. It signals that a method has been invoked at an illegal or inappropriate time. In other words, the
2 min read
DoubleStream.Builder add(double t) in Java with Examples
DoubleStream.Builder add(double t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built. Syntax: default DoubleStream.Builder add(double t) Parameters: This method accepts a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws Illeg
2 min read
LongStream.Builder add(long t) in Java
LongStream.Builder add(long t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built. Syntax: default LongStream.Builder add(long t) Parameters: This method accepts a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateE
2 min read
Pattern pattern() method in Java with Examples
The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression. Syntax: public String pattern() Parameters: This method does not accepts anything as parameter. Return Value: This
2 min read
Singleton Method Design Pattern in Java
In object-oriented programming, a java singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any inst
8 min read
Difference Between State and Strategy Design Pattern in Java
It is important for a java developer to clearly understand the difference between State and Strategy Design Pattern in Core Java application in order to make the proper use of them. Though both State and Strategy design patterns have a similar structure, and both of them are based upon the Open closed design principle, represents 'O' from SOLID des
3 min read
Difference Between Singleton and Factory Design Pattern in Java
Design patterns are essential tools for creating maintainable and scalable software. Two commonly used design patterns in Java are the Singleton and Factory patterns. This article provides an introduction to the Singleton and Factory design patterns with examples. Singleton Design Pattern in JavaThe Singleton pattern is a creational design pattern
3 min read
Java Singleton Design Pattern Practices with Examples
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. There are many ways this
6 min read
Spring - When to Use Factory Design Pattern Instead of Dependency Injection
Prerequisite: Factory Pattern vs Dependency Injection Factory Design Pattern and Dependency Injection Design both are used to define the interface-driven programs in order to create objects. Dependency Injection is used to obtain a loosely coupled design, whereas the Factory Pattern adds coupling, between objects, factories, and dependencies. In th
2 min read
Object Pool Design Pattern
The Object Pool Design Pattern is a creational design pattern that manages a pool of reusable objects to minimize the overhead of creating and destroying objects. It maintains a collection of initialized objects and provides mechanisms for clients to efficiently borrow and return objects from the pool. Important Topics for Object Pool Design Patter
9 min read
Pattern splitAsStream() Method in Java with Examples
splitAsStream() method of a Pattern class used to return a stream of String from the given input sequence passed as parameter around matches of this pattern.this method is the same as the method split except that what we get back is not an array of String objects but a stream. If this pattern does not match any subsequence of the input then the res
2 min read
Matcher pattern() method in Java with Examples
The pattern() method of Matcher Class is used to get the pattern to be matched by this matcher. Syntax: public Pattern pattern() Parameters: This method do not accepts any parameter. Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher. Below examples illustrate the Matcher.pattern() method: Example 1: // J
2 min read
Matcher usePattern(Pattern) method in Java with Examples
The usePattern() method of Matcher Class is used to get the pattern to be matched by this matcher. Syntax: public Matcher usePattern(Pattern newPattern) Parameters: This method takes a parameter newPattern which is the new pattern to be set. Return Value: This method returns a Matcher with the new Pattern. Exception: This method throws IllegalArgum
2 min read
Pattern compile(String) method in Java with Examples
The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern.compile() method.Syntax: public static Pattern compile(String regex) Par
2 min read
Article Tags :
Practice Tags :