The idea behind the Builder pattern is that
creating
that object.When you create a builder, and especially when you use one, you need to be aware of the reusability issue. Can you use a single instance of a builder to create multiple instances of the product? It is certainly easier to write one-shot builders or builders that need to be reset before reuse than it is to create completely reusable builders. The question is this: Which kind of builder are you creating or using?
Suppose each computer is made up of a display, a motherboard, and some drives
Even with this somewhat simplified model of, constructing a new instance of a Computer is tedious
# Build a fast computer with lots of memory...
motherboard = Motherboard.new(TurboCPU.new, 4000)
# ...and a hard drive, a CD writer, and a DVD
drives = []
drives << Drive.new(:hard_drive, 200000, true)
drives << Drive.new(:cd, 760, true)
drives << Drive.new(:dvd, 4700, false)
computer = Computer.new(:lcd, motherboard, drives)
Each builder has an interface that lets you specify the configuration of your new object step by step. In a sense, a builder is sort of like a multipart new method, where objects are created in an extended process instead of all in one shot.
Then we can consume the builder, and build the computer step by step
builder = ComputerBuilder.new
builder.turbo
builder.add_cd(true)
builder.add_dvd
builder.add_hard_disk(100000)
# Finally, you get the shiny new Computer instance from the builder:
computer = builder.computer
The GOF called the client of the builder object the director because it directs the builder in the construction of the new object (called the product). Builders not only ease the burden of creating complex objects but also hide the implementation details.
Imagine that our computer business expands into producing laptops along with traditional desktop machines. Thus we now have two kinds of products: desktop computers and laptops.