Design Patterns: Builder
Updated: Jul 12, 2021
Essentially this pattern is used when you need to build up a large and complex object. Instead of passing in all of the parameters ate the beginning (Don't do it, try to stick to three-four at max). This pattern enables you to create a complex object bit by bit, to separate away the hassle of trying to manage a large constructor/ method signature.
Again as before, link to code at the end of the post. Same one as the last design pattern sample yada, yada, yada. Here is a diagram of how the pattern is constructed:
This project is a little in-depth. So we need a situation. Our client is a Car manufacturer that needs us to help them build cars. First off lets design our car object and our builder's interface.
Codeward we go!!
Cool, now on to implementing our builder and creating our client, that will encapsulate our builder.
Great, what we have done is created a builder that builds our Car and a client that oversees the build process. So what now, well now we see how to implement it. The important part of this bit of code is in the cloning/ clearing of the built Car before it has been returned. The reason for this is that now, the constructor doesn't have to be called again to start of with an entirely new Car.
Simples! Right well... sorry to break it to you but, we can improve on this by making it fluent. What's fluent I hear you ask. This basically means
that we are going to be chaining our build calls together so that it's not so disparate.
And there you have it job done. A builder object that can be used to build objects. Now, there is a variation on this that uses recursive generics. I'm not sure if I'll cover it this year but, we will see.
I hope this helps you understand the builder pattern :)