The Builder Pattern

Image from Pexels

In this post we are going to see what the Builder Pattern is. Let’s get into it!


The Builder Pattern is a Creational Pattern that offers a solution to the telescoping constructor anti-pattern. It allows us to create different “flavors” of an object without polluting the constructor.

This pattern is useful when the construction process must allow different representations of an object or when the creation of an object involved a lot of steps.

The main difference from the Factory Pattern is that this last one should be used when the object creation is a one step-process.

Let’s make a quick example written with PHP and just for fun, let’s say we need to implement the Builder Pattern to manage our hero in our brand-new video game.

First, we define a Builder Interface:

interface BuilderInterface
{
public function addHair();
public function addArmor();
public function addWeapon();
public function build();
}

Then we can implement our interface:

class HeroBuilder implements BuilderInterface
{
public $name;
public $hair;
public $armor;
public $weapon;

public function __construct($name)
{
$this->name = $name;
}
public function addHair()
{
$this->hair = "Hero Hair";
}

public function addArmor()
{
$this->armor = "Hero Armor";
}

public function addWeapon()
{
$this->weapon = "Hero Weapon";
}

public function build()
{
return new Hero($this);
}
}

Finally we create a class for our hero:

class Hero
{
protected $name;
protected $hair;
protected $armor;
protected $weapon;

public function __construct($builder)
{
$this->name = $builder->name;
$this->hair = $builder->hair;
$this->armor = $builder->armor;
$this->weapon = $builder->weapon;
}

}

And we create our hero like so:

$hero = (new HeroBuilder("The Hero"))
->addHair()
->addArmor()
->addWeapon()
->build();

Mátyás Lancelot Bors

Written by

WebDeveloper / Writer / Musician / https://www.mlbors.com / https://medium.com/@mlbors

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade