As the name implies, a builder pattern is used to build objects. Sometimes, the objects we create can be complex, made up of several sub-objects or require an elaborate construction process. The exercise of creating complex types can be simplified by using the builder pattern. A composite or an aggregate object is what a builder generally builds.
Key consideration: The builder pattern might seem similar to the ‘abstract factory’ pattern but one difference is that the builder pattern creates an object step by step whereas the abstract factory pattern returns the object in one go.
xxxxxxxxxx
The Builder pattern is used to construct complex objects step by step. It separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
Example in ReactJS:
Imagine you're creating a form builder that allows users to dynamically add form fields.
// FormBuilder.js
const FormBuilder = () => {
const fields = [];
const addTextField = (label) => {
fields.push(<input type="text" placeholder={label} />);
};
const addCheckbox = (label) => {
fields.push(<input type="checkbox" /> <label>{label}</label>);
};
const getResult = () => fields;
return {
addTextField,
addCheckbox,
getResult,
};
};
// Usage
const formBuilder = FormBuilder();
formBuilder.addTextField("Name");
formBuilder.addCheckbox("Agree to terms");
const formFields = formBuilder.getResult();