Creational Design Patterns 2 - Builder Design Pattern
Builder design pattern helps creation of an object in a more readable and cleanable way. From the quotes of Gang of four -
“Separate the construction of a complex object from its representation so that the same construction process can create different representations.”
It is helpful when you have an object with different types of parameters .
Ex: lets say that we have an object with four fields , two fields is must to create object and other two fields is optional , we have to pass two mandatory fields in the constructor to create object and other two fields you can ignore .
Lets take example :)
val alertDialog : AlertDialog = AlertDialog.Builder(this) .setTitle("Builder Example") .setMessage("Builder implementation in Alert Dialog") .create();
you can see in above example , this class take context as mandatory parameter and the remaining parameters (setTitle and setMessage) is optional .
Builder Design Pattern is really great how !?
Consider we have form for user that need to fill his details . there are fields are mandtory and other is optional [name,email,phone] is mandatory and [age,address] is optional .
* First , if we need to make this task without using builder design pattern what will we do :
may the answer will be , you would create constructor with different parameters for creating the object .
With Builder Design Pattern the scenario is very good and helpful , lets go :
public class User{ private String name; private String email; private String phone; private int age; private String address; private Student(final StudentBuilder builder) { name = builder.name; email= builder.address; phone= builder.email; age= builder.phoneNumber; address= builder.passportNumber; } public static class StudentBuilder { private String name; private String email; private String phone; private String address; private int age; public StudentBuilder(String name, String email, String phone){ this.name = name; this.address = address; this.email = email; } public StudentBuilder setAddress(final String adress) { this.address= address; return this; } public StudentBuilder setAge(final int age) { this.age = age; return this; } public User create() { return new User(this); } }
}
Thanks for Reading ......
See you in other Pattern .