首頁  >  文章  >  後端開發  >  php設計模式 Builder(建造者模式)

php設計模式 Builder(建造者模式)

高洛峰
高洛峰原創
2016-11-30 09:34:291151瀏覽

複製程式碼如下:
/** 
* 建造者模式 

* 將一個複雜物件的建造與它的表示分離,使用同樣的建造過程可以創建不同的表示 
*/
class Product

public $_type = null; 
公$_size = null; ($type) 

echo "設定產品類型
"; 
$this->_type = $type; 


public function setSize($size) 

>"; 
$this->_size = $size; 

$this->_size = $size; 


public function setColor($color) 

echo "設定產品顏色
"; 

echo "設定產品顏色
";


$config = array(
"type"=>"襯衫", 
"size"=>"xl", 
"color"=>"red", 
); 

"color"=>"red", 
); 

"color"=>"red", 
);的處理
$oProduct = new Product(); 
$oProduct->setType($config['type']); 
$oProduct->setSize($config['size']); 
$oProduct->setSize($config['size']); 
$oProduct->setor( $config['color']); 


// 建立一個建構器類別
class ProductBuilder

var $_config = null; 
var $_object = null 🠎
. $this->_object = new Product(); 
$this->_config = $config; 


public function build() 

echo "--- 在建構器中---
" ; 
$this->_object->setType($this->_config['type']); 
$this->_object->setSize($this->_config['size']); 
$this-> _object->setColor($this->_config['color']); 


public function getProduct() 

return $this->_object; ); 
$objBuilder->build(); 
$objProduct = $objBuilder->getProduct(); 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn