Situation
You are going to create a User class with data name, dateOfBirth, gender, height, and weight. Other than name parameter, all others are optional. In such a situation, the general amateur solution is to provide multiple constructors for the class and make the code clumsy. Builder pattern tries to address this exact problem.
Builder Pattern
The arguments that needs to be passed to a complex object is made another object in itself. As that object makes sense only for the class it is simplifying, it is made a static subclass.
As you have seen above, you can declare a separate builder class within the specified class which sets all the parameters to default. Each option can be called separately and a separate build() method would create the required object. So the builder pattern simulates named optional parameters. Builder can also check whether all options are set right in the build() method.
Advantages:
1. Number of constructors become lesser.
2. If there is an additional optional parameter being added, builder needs very little change.
Disadvantage:
1. The darker side of Builder pattern is that the object creation becomes a bit complex.
You are going to create a User class with data name, dateOfBirth, gender, height, and weight. Other than name parameter, all others are optional. In such a situation, the general amateur solution is to provide multiple constructors for the class and make the code clumsy. Builder pattern tries to address this exact problem.
Builder Pattern
The arguments that needs to be passed to a complex object is made another object in itself. As that object makes sense only for the class it is simplifying, it is made a static subclass.
public class User { private String name; private Date dateOfBirth; private String gender; private Integer height; private Integer weight; public static class Builder { // Required parameter private String name; // Optional parameter private Date dateOfBirth; public Builder(String name) { this.name = name; } public Builder dateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; return this; } public User build() { return new User(this); } } private User(Builder b) { this.name = b.name; this.dateOfBirth = b.dateOfBirth; } } class TestUser { User u = new User.Builder("foo").dateofBirth(new Date()).build(); }
As you have seen above, you can declare a separate builder class within the specified class which sets all the parameters to default. Each option can be called separately and a separate build() method would create the required object. So the builder pattern simulates named optional parameters. Builder can also check whether all options are set right in the build() method.
Advantages:
1. Number of constructors become lesser.
2. If there is an additional optional parameter being added, builder needs very little change.
Disadvantage:
1. The darker side of Builder pattern is that the object creation becomes a bit complex.
No comments:
Post a Comment