/**
* @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);
/**
* 建造者模式最主的目的是消除其他对象的复杂创建过程,
* 而且在某个对象进行构造和配置方法时可以尽可以能地减少重复更改代码
*/
转载于:https://my.oschina.net/u/1246814/blog/512321