According to GoF and their great book “Design Patterns: Elements of Reusable Object-Oriented Software”, builder pattern:
„Separate the construction of a complex object from its representation so that the same construction process can create different representations.”
and it’s a part of an object creational design patterns.
Builder pattern is useful when the algorithm how to build an object is something independent of the parts that makes the object (methods that are building the object). That also defines another applicability of builder pattern: it’s helpful when there can be many ways of building complex objects.
Let’s start with some example and see how we can improve/refactor it by using builder patter.
Let’s assume we have that way of creating users:
There are few problems with that approach:
- it doesn’t look professional ;)
- we have very long list of params which limits us with the ways we can instantiate a new user. To do this, you can sent
nilfor certain params but it can look very messy soon,
- adding new params will only make the situation worse,
- logic how the object is build is hidden in its instantiation.
To extract the logic how the user is build we can use builder pattern here.
User class should be simple:
and we want to instantiate new user by doing this:
We are telling our builder (
UserBuilder) how to build new user by giving him exact plan (represented by the block in that example).
Two benefits that are obvious here: no long list of parameters and algorithm how the user is build is outside
UserBuilder has the knowledge how to build parts of the
User. It gives us some more digestible way of building new object(
set_as_active, …) than just instantiation of
User from the first example (we don’t have to know about some low level detail of what parts build a user object).
You can have different plans how to create a new user (blocks passed to
UserBuilder.build method) and you can be always sure that your builder (
UserBuilder) will know how to use your plan to build new object.
Want to know first about new articles from that blog?
Subscribe to my newsletter now! — http://eepurl.com/cVPm_v
If you like this article and consider it useful for you, please support it with 💚