Builder Design Pattern (Design Pattern-04)

Sanduns Sameera De Silva
3 min readJul 4, 2022

--

Builder is a Creational design pattern that allows you to build complicated objects step by step. The pattern enables you to create many kinds and representations of an object while using the same creation code.

https://media.geeksforgeeks.org/wp-content/uploads/uml-of-builedr.jpg

Product:- The product class specifies the sort of complicated object that will be produced by the builder pattern.

Builder:- This abstract base class defines all of the steps required to generate a product successfully. The real functionality of the builder is carried out in the concrete subclasses, therefore each phase is normally abstract. The final product is returned by the GetProduct method. A basic interface is frequently used in place of the builder class.

ConcreateBuilder:- Builder can be inherited by any number of concrete builder classes. These classes include the functionality required to produce a certain complex product.

Director:- The algorithm that develops the final product object is controlled by the Director class. A Director object is created, and its Construct method is called. An argument is included in the procedure to capture the precise concrete builder object that will be utilized to produce the product. The director then calls concrete building methods in the right order to produce the product object. When the procedure is finished, the GetProduct method of the builder object may be used to return the product.

Let’s consider an example:-

Consider the building of a home. The final end result (object) that will be returned as the outcome of the construction process is the home. There will be several steps, such as basement building, wall construction, and roof construction. After that, the entire home object is returned. You may create buildings with varied attributes here using the same technique.

HousePlan.java
House.java
HouseBuilder.java
IglooHouseBuilder.java
TipiHouseBuilder.java
CivilEngineer.java
Builder.java
Output

Advantages of Builder Design Pattern

i. The parameters to the constructor are reduced and are provided in highly readable method calls.

ii. Builder design pattern also helps in minimizing the number of parameters in the constructor and thus there is no need to pass in null for optional parameters to the constructor.

iii. The object is always instantiated in a complete state.

iv. Immutable objects can be built without much complex logic in the object-building process.

Disadvantages of Builder Design Pattern

i. The number of lines of code increases at least to double in the builder pattern, but the effort pays off in terms of design flexibility and much more readable code.

ii. Requires creating a separate ConcreteBuilder for each different type of Product.

--

--