Статья
Шаблон проектирования "Строитель"

Шаблон проектирования "Строитель"

14 декабря 2017
class Pizza
{
    protected $size;
    protected $cheese = false;
    protected $pepperoni = false;
    protected $tomato = false;

    public function __construct(PizzaBuilder $builder)
    {
        $this->size = $builder->size;
        $this->cheese = $builder->cheese;
        $this->pepperoni = $builder->pepperoni;
        $this->tomato = $builder->tomato;
    }
}

class PizzaBuilder
{
    public $size;
    public $cheese = false;
    public $pepperoni = false;
    public $tomato = false;

    public function __construct($size)
    {
        $this->size = $size;
    }

    public function addPepperoni()
    {
        $this->pepperoni = true;
        return $this;
    }

    public function addCheese()
    {
        $this->cheese = true;
        return $this;
    }

    public function addTomato()
    {
        $this->tomato = true;
        return $this;
    }

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

 

Использование:

$pizza = (new PizzaBuilder(30))->addPepperoni()->addTomato()->build();



Источники:

http://designpatternsphp.readthedocs.io/ru/latest/Creational/Builder/README.html
https://habrahabr.ru/company/mailru/blog/325492/