php设计模式之建造者模式

建造者模式

建造者设计模式的目的是消除其他对象的复杂创建过程。使用建造者设计模式不仅是最佳的做法,而且在摸个对象的构造和配置方法改变时候,可以尽可能的减少重复更改代码。

<?php
/**
 *productBuilder.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 = array('type'=>'shirt', 'size'=>'XL', 'color'='red');

$product = new product();
$product->setType($productConfigs['type']);
$product->setSize($productConfigs['size']);
$product->setColor($productConfigs['color']);
/**
 * 当product类发生改变时候,比如增加或者减少配置项,需要在所有实例化的地方更改代码。
 */

/**
 * productBuilder 不仅存储配置参数,而且存储一个实例化的新product实例。
 */
class productBuilder
{
    protected $_product = NULL;
    protected $_configs = array();

    public function __construct($configs){
        $this->_product = new product();
        $this->_xml = $configs;
    }

    public function build(){
        $this->_product->setSize($configs['size']);
        $this->_product->setType($configs['type']);
        $this->_product->setColor($configs['color']);
    }

    public function getProduct(){
        return $this->_product;
    }
}

$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();
原文地址:https://www.cnblogs.com/happig/p/5365884.html