<?php
/**
* 建造模式
* 功能:由于厨师经常做菜不是少放了油就是没盐,顾客很不满意,
* 为了提高服务质量,厨师们都按照以下程序做菜
*/
/**
* 具体产品:
* 做菜,最初就这一个类,厨师们乱放油盐
*/
class Cooking
{
//菜的所有配料
private $vegetables = array();
//为这道菜添加配料
public function add( $item )
{
if( is_array( $item ) )
{
$this->vegetables = array_merge( $this->vegetables , $item );
}
else
{
$this->vegetables[] = $item;
}
}
//显示这道菜用了些什么原料
public function show()
{
print_r( $this->vegetables );
}
}
/**
* 在抽象类中,把该放的东西定死,做任何菜都得要执行这个。我看他们还会忘记放盐了不
*/
abstract class CookingBuilder
{
//放油
abstract function setOil();
//放盐
abstract function setSalt();
//放其它佐料
abstract function setOthers();
//放菜
abstract function setVegetables();
abstract function getResult();
}
/**
* 一个具体的建造者,实现CookingBuilder接口,做土豆丝,
*/
class PotatoBuilder extends CookingBuilder
{
private $oil = '菜油';
private $salt = '盐一勺';
private $vegetables = '土豆丝';
private $others = array( '青椒' , '蒜' );
private $vegetablesObj;
public function __construct()
{
$this->vegetablesObj = new Cooking();
}
//放油
public function setOil()
{
$this->vegetablesObj->add( $this->oil );
}
//放盐
public function setSalt()
{
$this->vegetablesObj->add( $this->salt );
}
//放菜
public function setVegetables()
{
$this->vegetablesObj->add( $this->vegetables );
}
//放其它佐料
public function setOthers()
{
$this->vegetablesObj->add( $this->others );
}
public function getResult()
{
return $this->vegetablesObj;
}
}
/**
* 另一个具体的建造者,实现CookingBuilder接口,做西红柿炒蛋,
*/
class TomatoBuilder extends CookingBuilder
{
private $oil = '花生油';
private $salt = '盐半勺';
private $vegetables = '西红柿';
private $others = array( '白糖' , '鸡蛋' );
private $vegetablesObj;
public function __construct()
{
$this->vegetablesObj = new Cooking();
}
//放油
public function setOil()
{
$this->vegetablesObj->add( $this->oil );
}
//放盐
public function setSalt()
{
$this->vegetablesObj->add( $this->salt );
}
//放菜
public function setVegetables()
{
$this->vegetablesObj->add( $this->vegetables );
}
//放其它佐料
public function setOthers()
{
$this->vegetablesObj->add( $this->others );
}
public function getResult()
{
return $this->vegetablesObj;
}
}
/**
* 指挥者:在这里使用CookingBuilder
*/
class Director
{
private $directer;
public function init( $builder )
{
$this->directer = $builder;
$this->cooking();
}
public function cooking()
{
$this->directer->setOil();
$this->directer->setSalt();
$this->directer->setVegetables();
$this->directer->setOthers();
}
}
$director = new Director();
$potatoBuilder = new PotatoBuilder();
$tomatoBuilder = new TomatoBuilder();
$director->init( $potatoBuilder );
$potato = $potatoBuilder->getResult();
$potato->show();
$director->init( $tomatoBuilder );
$tomato = $tomatoBuilder->getResult();
$tomato->show();
?>