建造者

/**
 * @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);

/**
 * 建造者模式最主的目的是消除其餘對象的複雜建立過程,
 * 並且在某個對象進行構造和配置方法時能夠盡能夠能地減小重複更改代碼
 */
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息