PHP建造者模式程式碼範例詳解
<?php// 建造者模式class Product{private $size;private $color;private $type;public function setSize($size) {$this->size = $size;}public function setColor($color) {$this->color = $color;}public function setType($type) {$this->type = $type;}public function toString() {ob_start();echo 'Size: ', $this->size , '<br/>';echo 'Color: ', $this->color , '<br/>';echo 'Type: ', $this->type , '<br/>';return ob_get_clean();}}// 分別調用每個方法並不是最佳的做法$product = new Product();$product->setSize(100);$product->setColor('red');$product->setType('shirt');// echo $product;// -----------------------------------------------------------/** * 建造者模式 * 將一個複雜物件的構建與它的表示分離,使同樣的構建過程可以建立不同的表示 */class ProductBuilder{private $product;private $configs;public function construct($cfgs) {$this->configs = $cfgs;$this->product = new Product();}/** * 構建對象 */public function buildProduct() {$this->product->setSize($this->configs['size']);$this->product->setColor($this->configs['color']);$this->product->setType($this->configs['type']);}public function getProduct() {return $this->product;}}$cfgs = array('size'=>100,'color'=>'blue','type'=>'shirt');$builder = new ProductBuilder($cfgs);$builder->buildProduct();echo $builder->getProduct();