建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构造过程可以创建不同的表示。如果我们用了建造者模式,那么用户就只需指定需要建造的类型就可以得到它们,而具体建造的过程和细节就不需知道了.
class Bird
{
public $head;
public $wing;
public $foot;
public function show(){
echo '头的颜色:'.$this->head.'<br>';
echo '翅膀的颜色:'.$this->wing.'<br>';
echo '脚的颜色:'.$this->foot.'<br>';
}
}
abstract class BirdBuilder
{
protected $bird;
public function __construct()
{
$this->bird = new Bird();
}
abstract function BuildHead();
abstract function BuildWing();
abstract function BuildFoot();
abstract function GetBird();
}
class BlueBird extends BirdBuilder
{
public function BuildHead()
{
$this->bird->head = 'Blue';
}
public function BuildWing()
{
$this->bird->wing = 'gray';
}
public function BuildFoot()
{
$this->bird->foot = 'gray';
}
public function GetBird()
{
return $this->bird;
}
}
class RoseBird extends BirdBuilder
{
public function BuildHead()
{
$this->bird->head = 'Red';
}
public function BuildWing()
{
$this->bird->wing = 'gray';
}
public function BuildFoot()
{
$this->bird->foot = 'gray';
}
public function GetBird()
{
return $this->bird;
}
}
class Director
{
public function Construct($builder)
{
$builder->BuildHead();
$builder->BuildWing();
$builder->BuildFoot();
return $builder->GetBird();
}
}
$director = new Director();
$blueBird=$director->Construct(new BlueBird());
$blueBird->show();
建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时适用的模式