建造者模式主要在于创建一些复杂的对象。将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示的设计模式;
1 class Product { 2 private $_parts; 3 public function __construct() 4 { 5 $this->_parts = array(); 6 } 7 public function add($part) { 8 return array_push($this->_parts, $part); 9 } 10 } 11 12 /** 13 * 建造者抽象类 14 */ 15 abstract class Builder 16 { 17 public abstract function buildPart1(); 18 public abstract function buildPart2(); 19 public abstract function getResult(); 20 } 21 22 /** 23 * 具体建造者 24 * 实现其具体方法 25 */ 26 class ConcreteBuilder extends Builder { 27 private $_product; 28 public function __construct() 29 { 30 $this->_product = new Product(); 31 } 32 public function buildPart1(){ 33 $this->_product->add('Part1'); 34 } 35 public function buildPart2(){ 36 $this->_product->add('Part2'); 37 } 38 public function getResult(){ 39 return $this->_product; 40 } 41 } 42 /** 43 * 导演者 44 */ 45 class Director{ 46 public function __construct(Builder $builder) 47 { 48 $builder->buildPart1();//导演指挥具体建造者生产产品 49 $builder->buildPart2(); 50 } 51 } 52 53 54 //client 55 $buidler = new ConcreteBuilder(); 56 $director = new Director($builder); 57 $product = $buidler->getResult(); 58 echo '<pre>'; 59 var_dump($product); 60 echo '</pre>';