The builder pattern

The builder pattern is used to build a complex object by incrementally building simpler parts of it. We can imagine that a factory assembly line would work in a similar fashion. In that case, a product is assembled step-by-step with more and more parts, and at the end of the assembly line, the product is finished and ready to go.

One benefit of this pattern is that the builder code looks like a linear data flow and is easier for some people to read. In Julia, we may want to write something like this:

car = Car() |>
add(Engine("4-cylinder 1600cc Engine")) |>
add(Wheels("4x 20-inch wide wheels")) |>
add(Chassis("Roadster Chassis"))

Essentially, this is the exact functional pipe pattern described in Chapter 9, Miscellaneous Patterns. For this example, we can develop higher-order functions for building each part (such as the wheels, engine, and chassis). The following code illustrates how to create a curry (higher-order) function for creating wheels:

function add(wheels::Wheels)
return function (c::Car)
c.wheels = wheels
return c
end
end

The add function just returns an anonymous function that takes a Car object as input and returns an enhanced Car object. Likewise, we can develop similar functions for the Engine and Chassis types. Once these functions are ready, we can build a car by simply chaining these function calls together.

Next, we will discuss the prototype pattern.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.72