The Builder pattern Gang of Four description is provided in this video as: Separate the construction of a complex object from its representation so that the same construction process can create different representations. Reynald simplifies the definition as "a pattern that lets you separating the building process". Reynald then describes the class diagram for the pattern and then provides a real-world example along with its class diagram.
- [Narrator] The first pattern I'll review is a creational pattern called Builder. Now, the Gang of Four describes the Builder pattern as being used to separate the construction of a complex object from its representation so that the same construction process can create different representations. Alright, what are they really saying? All they're saying is that it's just a pattern that lets you separate and reuse a specific process to build something, like constructing an object.
You'll only want to do this when the construction process is complex. Otherwise, there's really no need to do this and it'll be an overkill. If we take a look at the class diagram, we can see the players that are involved. We have a Director that constructs an object using the Builder interface. And to the right of it, the Builder specifies an abstract interface for creating parts of a product object. Below that is the ConcreteBuilder, and that constructs and assembles parts of the product by implementing the Builder interface.
It also provides an interface for retrieving the Product. And lastly, to the righthand side is the Product which represents the complex object itself that's under construction. The ConcreteBuilder to the left of it builds the Product's internal representation and defines a process by which it's assembled. This is going to make much more sense with our example. And what we're going to do is demonstrate this Builder pattern in which different cars are assembled in a step by step fashion. We're going to have a CarFactory that uses CarBuilders to construct two types of cars in a series of steps.
So our diagram will look like this. The director on the upper lefthand corner is going to be our CarFactory. The builder is CarBuilder. Right below it, we'll have two concrete Builders, one that's called NotSoSuperCarBuilder and a SuperCarBuilder which is to the right. Those are the concrete builders. NotSoSuperCarBuilder is actually a lame car and another one which is an awesome car, SuperCarBuilder, to the right.
And the product itself is the Car. Let's check out the code. That's up next.
- What are design patterns?
- Who are the Gang of Four?
- Learning about the three categories of design patterns
- Builder pattern
- Adapter pattern
- Composite pattern
- Chain of Responsibility pattern
- Command pattern
- Interpreter pattern
- Mediator pattern
- Visitor pattern