Você está na página 1de 9

Builder Design Pattern

Builder: Overview
Intent
Separate the construction of a complex object from its representation so that the same construction process can create different representations

Think of a car factory


Boss tells workers (or robots) to build each part of a car Workers build each part and add them to the car being constructed

Builder: Participants
Builder
Specifies an abstract interface for creating parts of a Product object

ConcreteBuilder
Constructs and assembles parts of the product by implementing the Builder interface

Director
Constructs an object using the Builder interface

Product
Represents the complex object under construction Includes classes that define the constituent parts Gives interfaces for assembling the parts

Builder: Collaborations
Client creates Director object and configures it with a Builder Director notifies Builder to build each part of the product Builder handles requests from Director and adds parts to the product Client retrieves product from the Builder

Builder: Applicability
Use Builder when:
The algorithm for creating a complex object should be independent of the parts that make up the object and how theyre assembled The construction process must allow different representations for the object being constructed The building process can be broken down into discrete steps (difference between Builder and Abstract Factory)

Builder: Consequences
Lets you vary a products internal representation by using different Builders Isolates code for construction and representation Gives finer-grain control over the construction process

Builder: Implementation
Issues to consider:
Assembly and construction interface: generality Is an abstract class for all Products necessary?
Usually products dont have a common interface

Usually theres an abstract Builder class that defines an operation for each component that a director may ask it to create.
These operations do nothing by default (empty, non-virtual methods in C++)

Difference between Factory & Builder


The factory pattern defers the choice of what concrete type of object to make until run time. The builder pattern encapsulates the logic of how to put together a complex object so that the client just requests a configuration and the builder directs the logic of building it. The factory is concerned with what is made, the builder with how it is made. Abstract factory's emphasis is on families of product objects (either simple or complex). Builder returns the product as the final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

Conclusions
Builder:
Lets you vary how a product gets assembled. Can define a new kind of builder for a product to assemble it in a different way Client doesnt need to know anything about the construction process, nor the parts that make up a product.

Você também pode gostar