The Builder pattern
Let us go almost all the way back to the start of the chapter and take another look at the way we pass named arguments to a C++ function. Instead of a constructor with many arguments, we settled on an options object where each argument is explicitly named:
City GreensDale(City::Options() .SetCenter(City::KEEP) .SetBuildings(3) .SetGuard(1) .SetForge() );
Let us now focus on the Options
object itself, specifically, the way we construct it. The constructor does not create a finished object (that would just move the problem from the City
constructor to the Options
constructor). Instead, we build the object piece by piece. This is a particular case of a very general design pattern – the Builder.
Basics of the Builder pattern
The Builder design pattern is used whenever we decide that an object cannot be constructed in what we consider a complete state by the constructor alone. Instead, we write a helper...