Skip to main content

4_builder design pattern

What was the problem in factory design pattern?
We create a class and assign all responsibilities for object creation. This class have static method also called static factory.
Remember we pass parameters to factory method and these parameters will be pass to the next class constructor, whose object we want to create.

What was the problem?

The parameters we want to pass in next class constructor, first they all need to pass to factory method.
The order of the parameters matters. Might be some parameters are optional. Therefore management of parameters is very difficult.


Imagine you are building  a system for Car, Burger, Computer.
These system have
1. multiple parts.
2. can be created with different configuration
3. some parts are optional
4. You can't pass 10+ argument to construction order management start complex.

Without Builder pattern
Your constructor is become messy.

<?php
$car = new Car("Red", "SUV", true, true, false, "Auto", "Leather", true, false, true);  // 😵
?>

Disadvantages

Hard to read.
Error-prone.
Not Flexible(can't easily change the order and Skip the optional).

Using Builder pattern

Build object step-by-step.
Separate construction logic from object creation.
Multiple objects can be created using the same builder pattern.

Definition:

Builder design pattern is one of the creational design pattern that help you to build step by step creation of the object. Finally return object with desire attributes values.

Real Life Example Car building of Builder Design pattern.
Goal
we want to build a car with different parts like
Color,
Engine,
GPS,
Transmission,
Seats

Product Class: Car

<?php

class Car {
    public $color;
    public $engine;
    public $gps;
    public $seats;
    public $transmission;

    public function show() {
        echo "Car: $this->color, $this->engine, $this->gps, $this->seats, $this->transmission\n";
    }
}


?>


2. Builder Interface

<?php

interface CarBuilder {
    public function setColor($color);
    public function setEngine($engine);
    public function setGPS($gps);
    public function setSeats($seats);
    public function setTransmission($type);
    public function getCar(): Car;
}

?>


3. Concrete Builder

<?php

class SportsCarBuilder implements CarBuilder {
    private $car;

    public function __construct() {
        $this->car = new Car();
    }

    public function setColor($color) {
        $this->car->color = $color;
    }

    public function setEngine($engine) {
        $this->car->engine = $engine;
    }

    public function setGPS($gps) {
        $this->car->gps = $gps ? "With GPS" : "No GPS";
    }

    public function setSeats($seats) {
        $this->car->seats = $seats;
    }

    public function setTransmission($type) {
        $this->car->transmission = $type;
    }

    public function getCar(): Car {
        return $this->car;
    }
}


?>

4. Director (Optional)

<?php

class CarDirector {
    public function buildBasicSportsCar(CarBuilder $builder) {
        $builder->setColor("Red");
        $builder->setEngine("V8");
        $builder->setGPS(true);
        $builder->setSeats("Leather");
        $builder->setTransmission("Automatic");
    }
}


?>

5. Client Code

<?php

$builder = new SportsCarBuilder();
$director = new CarDirector();

$director->buildBasicSportsCar($builder);
$car = $builder->getCar();
$car->show();  // Output: Car: Red, V8, With GPS, Leather, Automatic

?>

    

🧙‍♂️ The Story of Building a Custom Sports Car
Once there is a factory name Brain motors which build cars, Now their is a demand of building of customized car. Customer want customized Sport Cars.
Now Every customer have different demand, some want auto engine, some want different seat color and some want GPS other not.
Factory workers become tired of answer the customer different demand.

Now factory manager decide to hire builder, which will build each part of the car step by step.
This code will always produce clean, customize cars.

🧱 
The Builder: SportCarBuilder

meet the build, who build the car piece by piece.

<?php

class SportsCarBuilder implements CarBuilder {
    private $car;

    public function __construct() {
        $this->car = new Car();  // starts with an empty car
    }

    public function setColor($color) {
        $this->car->color = $color;  // paints the car
    }

    public function setEngine($engine) {
        $this->car->engine = $engine;  // adds the engine
    }

    public function setGPS($gps) {
        $this->car->gps = $gps ? "With GPS" : "No GPS";  // adds GPS (optional)
    }

    public function setSeats($seats) {
        $this->car->seats = $seats;  // installs seats
    }

    public function setTransmission($type) {
        $this->car->transmission = $type;  // sets manual or automatic
    }

    public function getCar(): Car {
        return $this->car;  // gives the completed car
    }
}


?>



🧑‍💼 The Director (CarDirector)
Here is the man who know, have data(information) how to build different models of the car.
He will provide instruction to the builder to build specific car model.

<?php

class CarDirector {
    public function buildBasicSportsCar(CarBuilder $builder) {
        $builder->setColor("Red");
        $builder->setEngine("V8");
        $builder->setGPS(true);
        $builder->setSeats("Leather");
        $builder->setTransmission("Automatic");
    }
}

?>


👨‍💻 The Client (You!)

Here the client came to the factory and say 

"I want a Red Sports Car with leather seats, GPS, automatic transmission, and a V8 engine"

Manager Replies

"Let me call my director and builder and they will take care of it"

<?php

$builder = new SportsCarBuilder();      // builder shows up
$director = new CarDirector();          // director gives instructions
$director->buildBasicSportsCar($builder);
$car = $builder->getCar();              // you get your customized car
$car->show();                           // shows: Car: Red, V8, With GPS, Leather, Automatic

?>


Now
You(Client) have now worry how the car is building.
The car is building in step-by-step order.
The director control the recipe.
The cars are perfectly customized every time.
Now the factory producing more car, with well structure code, the customers are also happy. 

Real world application example
1. Ecommerce Project
In an ecommerce website, in creating order (check out) you have to get information like

1. Customer Info
2. Cart Item
3. Shipping Info
4. Discounts
5. Payment Method
6. Invoice
You don't want to constructor to get 10+ parameters.
You would do like that

<?php
$order = (new OrderBuilder())
    ->setCustomer($customer)
    ->addItems($cartItems)
    ->setShippingAddress($address)
    ->applyDiscount($code)
    ->setPaymentMethod("COD")
    ->build();

?>

2. Generating PDF or Document (Resume, Invoices, Repots)
Laravel use laravel dompdf , Snappy may internally use builder like logic.

<?php
$pdf = (new PdfBuilder())
    ->addHeader("Invoice #123")
    ->addTable($invoiceData)
    ->addFooter("Thanks for your business")
    ->build();
?>

3. Hotel Booking and Travel package

We have hotel management system where we have option to build custom travel packages.
1. Flight
2. Hotel
3. Cab
4. Activities
Now customer have many facility to get their desire custom package. No Need To Change The System.

<?php
$package = (new TravelPackageBuilder())
    ->addFlight("LHE to DXB")
    ->addHotel("Hilton")
    ->addTaxi("Airport Pickup")
    ->addActivity("Desert Safari")
    ->build();

?>

4. Database Query Builder (Laravel)
In Laravel we have query builder to step by step build query, using builder method.

<?php
DB::table('users')
  ->where('status', 'active')
  ->where('role', 'admin')
  ->orderBy('created_at', 'desc')
  ->limit(10)
  ->get();
?>

You are building the query step-by-step. 

5. Notification System

Suppose you are building the notification, where you build notification like as
set title, set message, set receipt, set channel, set schedule

The code will be look alike

<?php
$notification = (new NotificationBuilder())
    ->setTitle("Payment Due")
    ->setMessage("Your bill is due tomorrow.")
    ->setRecipient($user)
    ->setChannel("email")
    ->schedule("2025-05-23 10:00:00")
    ->build();

?>

6. HTML or FORM Builder (Laravel's form facade)
In Laravel you can build form adding each method on the builder class, On each method call form state change.

<?php
Form::open(['url' => '/submit'])
    ->label('Name')
    ->text('name')
    ->email('email')
    ->submit('Send')
    ->close();
?>














  

Comments

Popular posts from this blog

Install MariaDB Latest Version 11.4 in Red Hat Version 9

 This this post i will show you step by step the installation process of mariaDB in red hat version 9. Step1 Run the command to pull the latest updated packages on applications installed in your system. -dnf update If you get Kernal update than reboot the system -reboot Step2 Go to official mariaDB site Make mariadb repository in /etc/yum.repos.d Place the configuration in this file # MariaDB 11.4 RedHatEnterpriseLinux repository list - created 2024-09-24 11:12 UTC # https://mariadb.org/download/ [mariadb] name = MariaDB # rpm.mariadb.org is a dynamic mirror if your preferred mirror goes offline. See https://mariadb.org/mirrorbits/ for details. # baseurl = https://rpm.mariadb.org/11.4/rhel/$releasever/$basearch baseurl = https://mirrors.aliyun.com/mariadb/yum/11.4/rhel/$releasever/$basearch # gpgkey = https://rpm.mariadb.org/RPM-GPG-KEY-MariaDB gpgkey = https://mirrors.aliyun.com/mariadb/yum/RPM-GPG-KEY-MariaDB gpgcheck = 1 Now install the mariaDB with its dependencies package...

Linux Commands

  Linux Commands 1.  OS-Release -cat /etc/os-release -cat /etc/redhat-release show os //kernal information -uname  show kernal middleware It is intermediator between hardware and software. -uname  -r what is process architect. -uname -p To show all information -uname -a 2.  Date-CAL -date -cal 3.  Booting in Linux (Run-Levels) Shutdown/Close pc -init 0  Single user mode -init 1 Multiple user mode -init 2 Multiple user mode with network plus full support Not use -init 4 Graphical mode init 5 Reboot the system -init 6 4.  Target command in Linux (systemctl) With the help of target we can manage system specific as well as user specific task. Target command is system Control (systemctl). Basically it is utility, which build to replace 'init' command. What systemctl can do ?  We can find its all commands with the help of single command. write systemctl enter twice TAB button. //it will list all its commands. Show current system mode - systemctl...