建造者设计模式是什么?
PHP 基础面试题
<?php
//建造者设计模式定义了处理其他对象的复杂构建的对象设计。
class product{
protected $_type = '';
protected $_size = '';
protected $_color = '';
public function setType($type){
$this->_type = $type;
}
public function setSize($size){
$this->_size = $size;
}
public function setColor($color){
$this->_color = $color;
}
}
$productConfigs = ['type' => 'shirt', 'size' => 'XL', 'color' => 'red'];
$product = new product();
$product->setType($productConfigs['type']);
$product->setSize($productConfigs['size']);
$product->setColor($productConfigs['color']);
class productBuilder{
protected $_product = NULL;
protected $_configs = [];
public function __construct($configs){
$this->_product = new product();
$this->_xml = $configs;
}
public function build(){
$this->_product->setSize($this->_xml['size']);
$this->_product->setType($this->_xml['type']);
$this->_product->setColor($this->_xml['color']);
}
public function getProduct(){
return $this->_product;
}
}
$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();