# Builder Pattern

# Builder Pattern: Making Objects the Easy Way

## What is the Builder Pattern?

Imagine you go to a pizza shop. The person at the counter asks you:

* "What size pizza?"
    
* "Which base - thin or thick?"
    
* "Do you want cheese?"
    
* "Do you want tomatoes?"
    
* "Do you want onions?"
    
* "Do you want peppers?"
    
* "Do you want olives?"
    

Now, some things are **must-have** (like size and base), but other things are **your choice** (like toppings). You might want some toppings but not all.

**Builder Pattern** is like this pizza ordering system. It helps us create objects (things) when we have many options, and some are required while others are optional.

---

## Real-World Example: Ordering a Sandwich

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1767443557107/d82ab16e-6b33-41a7-954e-f7364d306b7d.png align="center")

Let's say you go to a sandwich shop.

**Must-have things:**

* Bread type (white or brown)
    
* Size (small or large)
    

**Optional things:**

* Cheese (yes or no)
    
* Lettuce (yes or no)
    
* Tomato (yes or no)
    
* Mayo (yes or no)
    

Without the Builder Pattern, you would need to tell the shopkeeper:

"I want a sandwich with white bread, large size, YES cheese, NO lettuce, YES tomato, NO mayo."

Every time, you have to say YES or NO for every single topping, even if you don't care about some of them.

**With Builder Pattern**, you only mention what you want:

"I want a sandwich with white bread, large size, and add cheese and tomato."

That's it! You don't need to worry about the things you don't want. The system handles it for you.

---

## What Problem Does Builder Pattern Solve?

### Problem 1: Too Many Constructors (Telescoping Constructor Problem)

Imagine you have a class called `Sandwich`. Without Builder Pattern, you might write many constructors like this:

```java
Sandwich(bread, size)
Sandwich(bread, size, cheese)
Sandwich(bread, size, cheese, lettuce)
Sandwich(bread, size, cheese, lettuce, tomato)
Sandwich(bread, size, cheese, lettuce, tomato, mayo)
```

This becomes messy! Too many combinations. Hard to remember which constructor to use.

### Problem 2: Passing Null or False for Everything

Another way is to have one big constructor:

```java
Sandwich(bread, size, cheese, lettuce, tomato, mayo)
```

But now, if you don't want lettuce or mayo, you have to pass:

```java
new Sandwich("white", "large", true, false, true, false)
```

See those `true` and `false`? Hard to remember what each one means! Confusing, right?

**Builder Pattern fixes both problems.**

---

## How Does Builder Pattern Work?

Think of Builder Pattern like filling a form step by step.

1. First, you fill in the **required fields** (like name and age).
    
2. Then, you **only fill the optional fields** you want (like phone number or email).
    
3. Finally, you click **Submit** button.
    

In programming, it works the same way:

1. Set the required fields
    
2. Set only the optional fields you need
    
3. Call `build()` method to create the final object
    

---

## Simple Code Example

Let's create a `Sandwich` class using Builder Pattern.

```java
// Main Sandwich class
class Sandwich {
    private String bread;      // required
    private String size;       // required
    private boolean cheese;    // optional
    private boolean lettuce;   // optional
    private boolean tomato;    // optional

    // Private constructor - only Builder can create Sandwich
    private Sandwich(SandwichBuilder builder) {
        this.bread = builder.bread;
        this.size = builder.size;
        this.cheese = builder.cheese;
        this.lettuce = builder.lettuce;
        this.tomato = builder.tomato;
    }

    // Builder class inside Sandwich class
    public static class SandwichBuilder {
        private String bread;      // required
        private String size;       // required
        private boolean cheese;    // optional, default false
        private boolean lettuce;   // optional, default false
        private boolean tomato;    // optional, default false

        // Constructor with required fields only
        public SandwichBuilder(String bread, String size) {
            this.bread = bread;
            this.size = size;
        }

        // Methods to set optional fields
        public SandwichBuilder addCheese() {
            this.cheese = true;
            return this;  // return "this" to allow chaining
        }

        public SandwichBuilder addLettuce() {
            this.lettuce = true;
            return this;
        }

        public SandwichBuilder addTomato() {
            this.tomato = true;
            return this;
        }

        // Final build method
        public Sandwich build() {
            return new Sandwich(this);
        }
    }
}
```

### How to Use This Code

```java
Sandwich mySandwich = new Sandwich.SandwichBuilder("white", "large")
                            .addCheese()
                            .addTomato()
                            .build();
```

---

## Understanding the Code Line by Line

### Part 1: Main Sandwich Class

```java
class Sandwich {
    private String bread;
    private String size;
    private boolean cheese;
    private boolean lettuce;
    private boolean tomato;
```

**Explanation:** These are the ingredients of our sandwich. `private` means no one can change them from outside.

---

```java
    private Sandwich(SandwichBuilder builder) {
        this.bread = builder.bread;
        this.size = builder.size;
        this.cheese = builder.cheese;
        this.lettuce = builder.lettuce;
        this.tomato = builder.tomato;
    }
```

**Explanation:** This is the constructor (the recipe). It's `private`, so only the Builder class can use it. It takes values from the Builder and creates the Sandwich.

---

### Part 2: Builder Class

```java
    public static class SandwichBuilder {
        private String bread;
        private String size;
        private boolean cheese;
        private boolean lettuce;
        private boolean tomato;
```

**Explanation:** This is our Builder class. It has the same ingredients as Sandwich. Think of it as the order form.

---

```java
        public SandwichBuilder(String bread, String size) {
            this.bread = bread;
            this.size = size;
        }
```

**Explanation:** This constructor asks only for the **required** things: bread and size. The optional things will be added later if needed.

---

```java
        public SandwichBuilder addCheese() {
            this.cheese = true;
            return this;
        }
```

**Explanation:** This method adds cheese to the sandwich. It returns `this` (which means the Builder itself), so you can keep adding more things in a chain.

---

```java
        public Sandwich build() {
            return new Sandwich(this);
        }
```

**Explanation:** This is like clicking the "Submit" button. It creates the final Sandwich using all the information you provided.

---

### Using the Builder

```java
Sandwich mySandwich = new Sandwich.SandwichBuilder("white", "large")
                            .addCheese()
                            .addTomato()
                            .build();
```

**Explanation step by step:**

1. `new Sandwich.SandwichBuilder("white", "large")` - Start the order with required items: white bread, large size
    
2. `.addCheese()` - Add cheese (optional)
    
3. `.addTomato()` - Add tomato (optional)
    
4. `.build()` - Finish and create the sandwich
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1767443696288/cd92b2bb-f44b-453d-afd2-541471b27364.png align="center")

Notice: We didn't add lettuce. That's okay! Builder handles it automatically (keeps it false).

---

## When to Use Builder Pattern

**Use it when:**

1. Your object has **many fields** (like 5 or more)
    
2. Some fields are **required**, some are **optional**
    
3. You want to make objects that **cannot be changed** after creation
    
4. You want **clean and readable** code
    

**Real-world examples:**

* Amazon shopping cart (add items one by one)
    
* Creating a user profile (name required, address optional, phone optional)
    
* Building a computer (processor required, graphics card optional)
    

---

## When NOT to Use Builder Pattern

**Avoid it when:**

1. Your object has only **2 or 3 simple fields**
    
2. All fields are **required**
    
3. The object needs to be **changed frequently** after creation
    

For simple objects, Builder Pattern is overkill (too much extra work for no benefit).

---

## Advantages (Good Things)

1. **Easy to read** - Code looks clean and simple
    
2. **No confusion** - You only set what you need
    
3. **No long constructors** - No need to remember the order of 10 parameters
    
4. **Safe objects** - Objects cannot be changed after creation
    

---

## Disadvantages (Not-So-Good Things)

1. **Extra code** - You need to write a separate Builder class
    
2. **Overkill for simple classes** - If your class has only 2 fields, Builder Pattern is too much work
    

---

## Real Examples Where Builder Pattern is Used

1. **Lombok** - A Java library that automatically creates Builder for you
    
2. **Amazon Cart** - When you add items to your cart one by one
    
3. **StringBuilder in Java** - Building strings step by step
    
4. **Android AlertDialog** - Creating dialogs with optional buttons and messages
    

---

## Summary in Simple Words

Builder Pattern is like ordering food at a restaurant:

1. You tell what you **must have** (like rice or bread)
    
2. You add **only the extras** you want (like cheese or sauce)
    
3. You place the order, and your food is ready
    

It makes creating objects easy and clean when you have many options. No need to pass `null` or `false` for things you don't want. Just add what you need, and the Builder handles the rest!

Think of it as building with LEGO blocks - add pieces one by one, and when you're done, you have your final creation!
