Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:See book
This is a pretty simple but very useful pattern, which allows us to create a complex object from simpler ones. It is very common to find ourselves in situations where we need to manually create complex objects over and over again, which lead us to assign properties to each and every one of them, and if such objects have to be built from some other objects, then we need to create those first in order to assign them to the main one we’re building. It is a long and tedious process, especially when it needs to be done frequently.
These are the components included in this pattern:
- IBuilder: The use of this component is not mandatory, however, it is recommended for specifying a common interface for all the Builder objects we're going to define in our application. It could be an interface for only defining a build method.
- ObjectBuilder: This is the class we’ll use for creating the TargetObject. This class should inherit from IBuilder and implement the build method, which is going to be used for creating the TargetObject. As a general rule, all the methods in this class return an instance of themselves in order to speed up the creation process. Usually, they are created as internal classes of TargetObject.
- TarjetObjet: It represents the object we want to create with the aid of the ObjectBuilder, this can be a simple class or a complex class containing many objects.
- OtherObjets: They represent the objects we may create when the ObjectBuilder builds the TargetObject.
- The client creates an instance of the ObjectBuilder .
- The client executes step 1 in the ObjectBuildercreation.
- Internally, TargetObject is created by the ObjectBuilder.
- The client executes step 2 in the ObjectBuildercreation.
- Internally, OtherObjectA is created by the ObjectBuilder.
- The client executes step 3 in the ObjectBuildercreation.
- Internally, OtherObjectB is created by the ObjectBuilder.
- The client requests ObjectBuilder for the creation of the TargetObject, this takes all the previously created objects, assigns them to TargetObject and returns them.
By implementing the Builder design pattern, we are going to solve a classic problem, that is, building a complex object with the aid of a Builder class, which will allow us to create the entire structure of an employee, along with all of its information, such as address, phone numbers, contacts, etcetera.