DEV Community

Cover image for Design Patterns Simplified: Part 7 – Builder Pattern (a.k.a. “Build It Step by Step”)
Prateek Prabhakar
Prateek Prabhakar

Posted on • Edited on • Originally published at Medium

Design Patterns Simplified: Part 7 – Builder Pattern (a.k.a. “Build It Step by Step”)

Builder Pattern belongs to the Creational category of design patterns.

Why? Because it's all about controlling how complex objects are created, especially when they require multiple steps or configurations.

Let’s take an example of Ordering a Pizza

Say you are ordering a Pizza from your favorite Pizzeria. You don't just get a default pizza. You choose,
Size: Small / Medium / Large
Crust: Thin / Cheese Burst / Stuffed
Toppings: Paneer, Mushrooms, Olives, Extra Cheese...

Each customer builds their pizza step by step, and a chef assembles the final result.
That is exactly what the Builder Pattern does in code i.e. you define each step, but assembly is done for you behind the scenes.


Wait… Doesn’t a Constructor Already Do That?

If you are familiar with Constructors we have in various programming languages, does this scenario look familiar? Constructor does the same operation, isn't it? It is the responsibility of constructor to add these "toppings" during object creation.

Then why do we need this additional pattern?

In simple objects, constructors work fine. But what if your object has,

  • 8 optional parameters,
  • some parameters are dependent on others, or
  • construction is complex.

That is when a constructor becomes confusing, just like, new Pizza(size, crust, true, false, true, false, true).
Instead, the Builder Pattern gives you readable, flexible, and controlled construction.


What is the Builder Pattern?

It is a design pattern that lets you construct complex objects step by step, without needing to pass everything into one constructor.
In short, it separates object construction from its representation.

The Notification System

Let’s say you are building a Notification system for your app, that sends different types of notifications based on certain domain events.

Class Notification
    Property Title
    Property Message
    Property IsEmailEnabled
    Property IsSMSEnabled
    Property IsPushEnabled

    Method Show()
        Print("Notification: " + Title)
Enter fullscreen mode Exit fullscreen mode

What does the code look like?

Without the builder pattern, the constructor is bloated,

// The ugly constructor
notification = new Notification("Offer Alert", "Big sale today!", 
true, false, true)
Enter fullscreen mode Exit fullscreen mode

With the builder pattern, things look much smoother,

// Step 1: Define the Builder
Class NotificationBuilder
    Constructor()
        this.notification = new Notification()

    Method SetTitle(title)
        notification.Title = title
        Return this

    Method SetMessage(message)
        notification.Message = message
        Return this

    Method EnableEmail()
        notification.IsEmailEnabled = true
        Return this

    Method EnableSMS()
        notification.IsSMSEnabled = true
        Return this

    Method EnablePush()
        notification.IsPushEnabled = true
        Return this

    Method Build()
        Return notification

//caller logic
notification = new NotificationBuilder()
                    .SetTitle("Big Sale!")
                    .SetMessage("50% off on all items.")
                    .EnableEmail()
                    .EnablePush()
                    .Build()

notification.Show()
Enter fullscreen mode Exit fullscreen mode

What did we achieve?

  • Object gets built step-by-step
  • Fluent & readable API
  • Construction is separated from representation
  • Optional fields handled gracefully
  • Future changes to object won’t break client code

When Should You Use Builder Pattern?

  • Object creation is complex
  • You have many optional parameters
  • You want clear, readable & flexible code
  • Construction process must be controlled in steps

Use Cases?

  • Building configuration objects
  • UI component creation
  • Complex HTTP request setup
  • Report generation pipelines
  • Query builders (SQL/NoSQL)

To summarize, it would be apt to say,

Builder Pattern helps in constructing complex objects step by step using a clean and flexible approach, keeping your code readable, modular, and easy to maintain.

Hope this helped you "build" a solid understanding of the Builder Pattern!

Next up in the series: Prototype Pattern. Lets meet there! But before going, there is a bonus section below.


BONUS

If you’ve read my post on the Decorator Pattern (and if not, check it out here), you might be wondering, aren’t they similar?

They look alike, but are fundamentally different.
Here’s a quick comparison,

difference_builder_decorator

To summarize the differences, you should use the Builder Pattern when you want to create something complex, step by step. On the contrary, use Decorator Pattern when you want to extend or modify behavior, without altering the original object.

Top comments (0)