Design Pattern — Builder

Sujit Tripathy
2 min readJan 10, 2022

This is the first chapter of the design pattern series. In this series I will be covering various design pattern and when to apply them at different use cases while implementing in a real-world project. Knowing a specific pattern one thing and apply the pattern to a specific use case while implementing a use case is important, and knowing when to apply a pattern and when not to apply by force without any need.

In this post I will cover builder pattern with an example and how it will help to create a complex object with fluent API rather complex constructor.

Let’s take an example. We are trying to create a Product object where there could be multiple attributes and some products are eligible for certain attributes and some are not (example, for hazardous material only applies to certain product). To create an Object with different combination we need constructor of different combinations so, that client can call the appropriate constructor and create the object. This solves the purpose however, you could imagine how quick this can gets messy with new attribute addition to the product we need to change the constructor (which will lead to compile time error and code refactoring), or add new constructor (by coping existing one)

To solve the above readable and modularity factor of the code, Builder pattern can be applied. The object will be created in a piecemeal way based on the attribute it required so, based on the client’s need appropriate object can be created.

To create the Product object via builder pattern, need to follow the below code. Below is one sample code is given however, in the similar way Product object can be created for the suitable attribute which is required for the object.

Thanks for reading and I hope you find this useful. In the future blogs, I will be sharing other commonly used pattern on software development and how to utilize the best practices while implementing a feature

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Sujit Tripathy
Sujit Tripathy

Written by Sujit Tripathy

Engineering @ Walmart Global Tech | Tech Enthusiast | Learner

No responses yet

Write a response