Hi, Today we will discuss here why, how and where we use the builder design pattern in swift or any kind of language. Builder design pattern is used to reduce the complexity of the code, it increases the readability of code for other developers, make more scalable, easy to do modification in the code. 

According to Wikipedia, “The Builder is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns(GOF).”

The core idea behind the builder pattern is that the process of setting up an object is performed by a dedicated Builder type, rather than by the object itself

Here are the example of builder design Pattern that how we can use.

For e.g. Suppose we have POJO class contain the number of parameters which is declared as private. According to the private definition, we can retrieve and get the value of the private variable with setter and getter method only. So we have the method which will set the value of the variable as well as retrieve the value of that variable. (as Shown below)

In above model class consist two variable names and address also we have an initializer (init) method (called Constructor). In init method, we set the value of name and address. Now we make the clone of that class which consists the same number of variable, that class will be called builder class. In Builder Class, all the function will return the object to its self only.  

In Builder class, there is builder function with a return type of POJO class (i.e. Model) which called the init method of ModClass.s .

Advantage Of Builder Design Pattern

  • The parameters to the constructor are reduced and are provided in highly readable method calls.
  • Builder design pattern also helps in minimizing the number of parameters the in the constructor and thus there is no need to pass in null for optional parameters to the constructor.
  • An object is always instantiated in a complete state
  • Immutable objects can be built without much complex logic in object building process.

Disadvantage of Builder Design Pattern

  • The number of lines of code increases at least to double in builder pattern, but the effort pays off in terms of design flexibility and much more readable code.
  • Requires creating a separate ConcreteBuilder for each different type of Product.


I hope after reading this article you have cleared idea (or idea at all) about the Builder pattern. I do, so I guess it a is success