knowledge/technology/dev/programming/patterns/creational/Builder Pattern.md
2024-01-17 09:00:45 +01:00

27 lines
No EOL
2.5 KiB
Markdown

---
obj: concept
---
# Builder Pattern
## **Description:**
The Builder Pattern is a creational design pattern used to construct a complex object step by step. It separates the construction of an object from its representation, allowing you to create different variations of the same object with a clear and consistent API. This pattern is particularly useful when an object has many optional components or configuration settings.
**How it's Used:**
1. **Builder Interface**: Define an abstract builder interface that declares methods for constructing different parts of the complex object. These methods should cover all possible configurations.
2. **Concrete Builders**: Create concrete builder classes that implement the builder interface. Each concrete builder is responsible for building a specific variant of the complex object.
3. **Product**: Define the complex object (the product) that you want to create. This object should have a way to accept values or components set by the builder.
4. **Director (Optional)**: You can create a director class (optional) that orchestrates the construction process using a specific builder. The director simplifies client code by providing a higher-level interface to construct the object.
5. **Client Code**: In your application, use the builder to construct the complex object step by step. You can chain method calls together for a more fluent and readable construction process.
## **Example:**
Consider building a `Computer` object with various optional components such as a processor, memory, storage, and graphics card. Here's how the Builder Pattern can be applied:
- **Builder Interface**: Define an `ComputerBuilder` interface with methods like `setProcessor`, `setMemory`, `setStorage`, and `setGraphicsCard`.
- **Concrete Builders**: Create concrete builder classes like `GamingComputerBuilder` and `OfficeComputerBuilder`, both implementing the `ComputerBuilder` interface. Each builder knows how to construct a specific type of computer.
- **Product**: Define the `Computer` class with fields for processor, memory, storage, and graphics card, and a constructor to initialize these fields.
- **Director (Optional)**: Create a `ComputerDirector` class that takes a `ComputerBuilder` as a parameter. The director can provide higher-level methods like `buildGamingComputer` or `buildOfficeComputer`.
- **Client Code**: In your application, use the builder to construct a computer with the desired components:
```java
ComputerBuilder builder = new GamingComputerBuilder();
Computer gamingComputer = builder.setMemory(16).buildComputer();
```