Builder Pattern in java
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.
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.
Output is guaranteed to be one of below:
id = 1, name = Ram, address = Noida
id = 2, name = Shyam, address = Delhi
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.