Home Web Front-end JS Tutorial Mastering the Builder Design Pattern: Simplifying Complex Object Creation

Mastering the Builder Design Pattern: Simplifying Complex Object Creation

Nov 12, 2024 am 06:28 AM

Mastering the Builder Design Pattern: Simplifying Complex Object Creation

Introduction

All of us, as developers, have encountered situations where we need to create an object. The problem with trying to design a generic class for this object is that it can take multiple forms. A simple example: the User class of a platform. For a regular user, we might only need an email and a username. However, for a platform administrator, additional attributes like a phone number might be required. We could also have a Premium user, where an extra field like a credit card number is needed, and so on.

So, how can we proceed in a generic way?

Faced with this problem, the developer community agreed on a popular creation pattern: the Builder Design Pattern. This pattern involves separating the construction of a complex object from its representation, allowing multiple object variants to be created using the same construction process.

This pattern is especially useful with objects that have many attributes, some of which may be optional for certain cases but not for others, or for objects that require a detailed initialization process. It allows for the flexible, step-by-step creation of objects without making the code overly complex or the constructor too overloaded.

Sections We Will Cover

  1. What is the Builder Pattern?
  2. When you should use it?
  3. Real-World Examples of Builder Use
  4. Why this pattern is so important?
  5. Conclusion ## What is the Builder Pattern? The Builder Design Pattern is a creational design pattern that allows for the controlled and flexible construction of complex objects. Instead of having a constructor that takes a large number of parameters, the builder provides a smooth interface to create objects step by step. It is useful when the object has many attributes, specific construction steps, or multiple possible configurations.

When you should use it?

The Builder Design Pattern is particularly useful in the following cases:

  1. If an object has many attributes, some of which are optional: Going back to the problem we posed at the beginning of this article, let’s consider the User class. Based on the logic we described, if we instantiate this User class, we could have different cases: for a regular user, normalUser = new User("houda", "houda@gmail.com", null, null), for an admin adminUser = new User("houda", "houda@gmail.com", "0657...", null), and for a premium user, premiumUser = new User("houda", "houda@gmail.com", null, "1234..."). This results in many null values in the instantiation.

  2. Objects with a multi-step creation process: An example is a Order class. The first step is to place the order, which is then prepared, and finally delivered. Preparing an order may require multiple steps, and to ensure the correct order of construction, the builder design pattern is very useful.

  3. Supporting multiple representations of the same object: For example, a Clothing class that has attributes for fabric, color, and brand. A clothing item can be a Pants, T-Shirt, or other types. Here, the builder pattern helps create different representations of the same base class.

Real-World Examples of Builder Use

for each case we have seen in the section before we will see the implementation of the builder

  1. If an object has many attributes, some of which are optional:
class User {
    username: string;
    email: string;
    phoneNumber?: string;
    creditCard?: string;

    private constructor(builder: UserBuilder) {
        this.username = builder.username;
        this.email = builder.email;
        this.phoneNumber = builder.phoneNumber;
        this.creditCard = builder.creditCard;
    }

    public static get Builder() {
        return new UserBuilder();
    }
}

class UserBuilder {
    username!: string;
    email!: string;
    phoneNumber?: string;
    creditCard?: string;

    public setUsername(username: string): UserBuilder {
        this.username = username;
        return this;
    }

    public setEmail(email: string): UserBuilder {
        this.email = email;
        return this;
    }

    public setPhoneNumber(phoneNumber: string): UserBuilder {
        this.phoneNumber = phoneNumber;
        return this;
    }

    public setCreditCard(creditCard: string): UserBuilder {
        this.creditCard = creditCard;
        return this;
    }

    public build(): User {
        return new User(this);
    }
}

// Usage
const normalUser = User.Builder
    .setUsername("houda")
    .setEmail("houda@gmail.com")
    .build();

const adminUser = User.Builder
    .setUsername("houda")
    .setEmail("houda@gmail.com")
    .setPhoneNumber("0657....")
    .build();

const premiumUser = User.Builder
    .setUsername("houda")
    .setEmail("houda@gmail.com")
    .setCreditCard("1234....")
    .build();

Copy after login
  1. Objects with a multi-step creation process:
class Order {
    private state: string;

    private constructor(builder: OrderBuilder) {
        this.state = builder.state;
    }

    public static get Builder() {
        return new OrderBuilder();
    }

    public getState(): string {
        return this.state;
    }
}

class OrderBuilder {
    state: string = "Placed";

    public prepareOrder(): OrderBuilder {
        if (this.state === "Placed") {
            this.state = "Prepared";
        }
        return this;
    }

    public deliverOrder(): OrderBuilder {
        if (this.state === "Prepared") {
            this.state = "Delivered";
        }
        return this;
    }

    public build(): Order {
        return new Order(this);
    }
}

// Usage
const completedOrder = Order.Builder
    .prepareOrder()
    .deliverOrder()
    .build();
console.log(completedOrder.getState()); // "Delivered"

Copy after login
  1. Supporting multiple representations of the same object:
class Clothing {
    type: string;
    fabric: string;
    color: string;
    brand: string;

    private constructor(builder: ClothingBuilder) {
        this.type = builder.type;
        this.fabric = builder.fabric;
        this.color = builder.color;
        this.brand = builder.brand;
    }

    public static get Builder() {
        return new ClothingBuilder();
    }
}

class ClothingBuilder {
    type!: string;
    fabric!: string;
    color!: string;
    brand!: string;

    public setType(type: string): ClothingBuilder {
        this.type = type;
        return this;
    }

    public setFabric(fabric: string): ClothingBuilder {
        this.fabric = fabric;
        return this;
    }

    public setColor(color: string): ClothingBuilder {
        this.color = color;
        return this;
    }

    public setBrand(brand: string): ClothingBuilder {
        this.brand = brand;
        return this;
    }

    public build(): Clothing {
        return new Clothing(this);
    }
}

// Usage
const tShirt = Clothing.Builder
    .setType("T-Shirt")
    .setFabric("Cotton")
    .setColor("Blue")
    .setBrand("BrandA")
    .build();

const pants = Clothing.Builder
    .setType("Pants")
    .setFabric("Denim")
    .setColor("Black")
    .setBrand("BrandB")
    .build();

Copy after login

Why this pattern is so important?

The Builder Design Pattern is important for several key reasons, especially when it comes to managing the complexity of object creation. Here's why it's so valuable:

  1. Handling Complex Objects

When an object has many attributes, some of which may be optional or need to be set in a specific order, the Builder Pattern provides a clear and structured way to create the object.

  1. Improves Code Readability and Maintainability

By separating the object creation logic from the object itself, the Builder Pattern makes the code more readable and easier to maintain.

  1. Reduces Constructor Overloading

Instead of having multiple constructors with different combinations of parameters, the Builder Pattern eliminates the need for constructor overloading.

  1. Clear Separation of Concerns

The builder separates the construction of an object from its representation. This means that you can change how the object is constructed without affecting its representation, or vice versa.

Conclusion

The Builder Design Pattern is an essential tool for developers dealing with complex object creation. By breaking down the construction process into clear, manageable steps, it improves code readability, maintainability, and flexibility. Whether you're working with objects that have many attributes, require multi-step construction, or need to support multiple configurations, the Builder Pattern provides an elegant solution that prevents over-complicated constructors and reduces errors.

The blog covered:

  1. What is the Builder Pattern?
  2. When you should use it?
  3. Real-World Examples of Builder Use
  4. Why this pattern is so important?

The above is the detailed content of Mastering the Builder Design Pattern: Simplifying Complex Object Creation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles