Background: Xiao CAI and Big Bird go to a food stall for a midnight snack. They order two stir-fried noodles. Xiao CAI’s is delicious, but Big Bird forgot to put salt in it. As a result, two fried noodles from the same chef taste different.

McDonald’s and KFC taste the same all over the country, because they have strict production process specifications.

Later it was suggested that in order to build a human being, five senses, feet and hands (which can be defined abstractly) must be present. However, height and height need to be declared separately (to inherit the previous abstract class).

Let’s start with the definition:

When we need to instantiate a complex class (such as a person) to obtain objects of different structural types and internal states, we can encapsulate their instantiation operation logic with different classes, which we call builders.

demand

The first requirement is to create a person with big eyes and a person with small eyes, so let’s create a Person class

When we want to create different types of people, people have different attributes. If we extend more attributes later, we will have to modify the original Person class, violating the open close principle.

\

Step 1: Create the Builder class

But if you think about it, a normal person has hands, feet, and a body. So how do we do that with the builder pattern? Let’s just abstract this guy out.

\

Step 2: Create a concrete builder class

When we create a fat man, we inherit the builder class.

We can construct the basic parts of a person’s body (because it’s necessary),

The part in the red box could not be added. Later I figured out that the expanded part would not be put into the Director class because the Director class is needed to create people.

Step 3: Create guidance classes

This class instructs us how to create objects. Okay

Client code

\

Conclusion:

Builder is the abstract interface specified by the parts that create a Product object. Like abstract people

Concretebuilders are concrete builders that implement the Builder interface and construct and assemble individual parts (body, hand, foot). Such as fatty

Diretor is the conductor, and the user can manipulate the conductor, passing in requirements (fat or thin) to build the product.

The Builder model is typically used to create complex objects that are built in a stable order (first body, then hand, then foot) but face complex changes (fat and thin people).

The advantage is that you can separate the build code from the presentation code. Because the Builder hides how the product is assembled, if you need to change the internal representation of a product, you only need to define a specific Builder.