/** * @author v.r And * * @example * 建造者 * 建造者设计模式定义了处理其余对象的复杂构建对象设计 * 列子: * 以商品为列子 * * @copyright copyright information * */ $productCofigs = array( 'type'=>'shirt', 'size'=>'xl', 'color'=>'red', ); class Product { protected $type = ''; protected $size = ''; protected $color = ''; public function setType ($type) { $this->type = $type; } public function setColor ($color) { $this->color = $color; } public function setSize ($size) { $this->size = $size; } } //建立商品对象 //$Product = new Product(); //$Product->setType($productCofigs['type']); //$product->setColor($productCofigs['color']); //$product->setSize($productCofigs['size']); /** * 以上是建立一商品对象时候的操做 * 问题: * 建立对象时候分别调用每一个方法是否是必要的合适的呢? * 若是不分别调用咱们应该选取什么方式来作呢? * 建造模式是否能解决问题以上顾虑 */ class ProductBuilder { protected $product = NULL; protected $configs = array(); public function __construct($configs) { $this->product = new Product(); $this->configs = $configs; } //构建 public function build() { $this->product->setSize($this->configs['size']); $this->product->setType($this->configs['type']); $this->product->setColor($this->configs['color']); } public function getProduct() { return $this->product; } } /** * build() 方法隐藏product对象的实际方法调用 * 若是product类之后会发生改变,只是须要修改build()方法 * */ $builder = new ProductBuilder($productCofigs); $builder->build(); $product = $builder->getProduct(); var_dump($product); /** * 建造者模式最主的目的是消除其余对象的复杂建立过程, * 并且在某个对象进行构造和配置方法时能够尽能够能地减小重复更改代码 */