<?php
// 当一个对象可能有几种情况,避免构造函数伸缩时使用。
// 与工厂模式的主要区别在于: 当创建是一个一步过程时,将使用工厂模式,
// 而在创建是一个多步过程时,将使用构建器模式。
// php 技术群:781742505
/**
* Class Burger
*/
class Burger
{
/**
* @var int
*/
protected $size;
/**
* @var bool
*/
protected $cheese = false;
/**
* @var bool
*/
protected $pepperoni = false;
/**
* @var bool
*/
protected $lettuce = false;
/**
* @var bool
*/
protected $tomato = false;
/**
* Burger constructor.
*
* @param BurgerBuilder $builder
*/
public function __construct(BurgerBuilder $builder)
{
$this->size = $builder->size;
$this->cheese = $builder->cheese;
$this->pepperoni = $builder->pepperoni;
$this->lettuce = $builder->lettuce;
$this->tomato = $builder->tomato;
}
}
/**
* Class BurgerBuilder
*/
class BurgerBuilder
{
/**
* @var int
*/
public $size;
/**
* @var bool
*/
public $cheese = false;
/**
* @var bool
*/
public $pepperoni = false;
/**
* @var bool
*/
public $lettuce = false;
/**
* @var bool
*/
public $tomato = false;
/**
* BurgerBuilder constructor.
*
* @param int $size
*/
public function __construct(int $size)
{
$this->size = $size;
}
/**
* @return $this
*/
public function addPepperoni()
{
$this->pepperoni = true;
return $this;
}
/**
* @return $this
*/
public function addLettuce()
{
$this->lettuce = true;
return $this;
}
/**
* @return $this
*/
public function addCheese()
{
$this->cheese = true;
return $this;
}
/**
* @return $this
*/
public function addTomato()
{
$this->tomato = true;
return $this;
}
/**
* @return Burger
*/
public function build(): Burger
{
return new Burger($this);
}
}
$burger = (new BurgerBuilder(14))
->addPepperoni()
->addLettuce()
->addTomato()
->build();
建造者模式
最新推荐文章于 2022-08-08 11:56:05 发布