Chapter 9: Builder Pattern
大綱
When should you use it?
The builder pattern allows you to create complex objects by providing inputs step-by-step, instead of requiring all inputs upfront via an initializer. This pattern involves three main types:
The director: accepts inputs and coordinates with the builder. This is usually a view controller or a helper class that’s used by a view controller.
The product: is the complex object to be created.
This can be either a struct or a class, depending on desired reference semantics. It’s usually a model, but it can be any type depending on your use case.
The builder: accepts step-by-step inputs and handles the creation of the product.
This is often a class, so it can be reused by reference.”

When should you use it?
Use the builder pattern when you want to create a complex object using a series of steps.
This pattern works especially well when a product requires multiple inputs.
Playground example
目標: hamburger builder
The product could be a hamburger model, which has inputs such as meat selection, toppings and sauces.
The director could be an employee object, which knows how to build hamburgers, or it could be a view controller that accepts inputs from the user.
Product
Builder
Director
What should you be careful about?
The builder pattern works best for creating complex products that require multiple inputs using a series of steps.
If your product doesn’t have several inputs or can’t be created step by step, the builder pattern may be more trouble than it’s worth.
Instead, consider providing convenience initializers to create the product.
Tutorial project
Key points
The builder pattern is great for creating complex objects in a step-by-step fashion. It involves three objects: the director, product and builder.
The director accepts inputs and coordinates with the builder; the product is the complex object that’s created; and the builder takes step-by-step inputs and creates the product.
Last updated