2.5 KiB
2.5 KiB
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:
- 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.
- 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.
- 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.
- 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.
- 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 likesetProcessor
,setMemory
,setStorage
, andsetGraphicsCard
. - Concrete Builders: Create concrete builder classes like
GamingComputerBuilder
andOfficeComputerBuilder
, both implementing theComputerBuilder
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 aComputerBuilder
as a parameter. The director can provide higher-level methods likebuildGamingComputer
orbuildOfficeComputer
. - Client Code: In your application, use the builder to construct a computer with the desired components:
ComputerBuilder builder = new GamingComputerBuilder();
Computer gamingComputer = builder.setMemory(16).buildComputer();