Design Patterns Reference: Builder

“The Builder Design Pattern defines the design of an object that handles the complex building of another object.”

/**
* the Builder Pattern
* creates objects
* so that only its build method need be modified
* if the class it builds changes in the future
* and to automate object instantiation according to requirements
*/

/**
* class that could change with time
*/

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;
}
}

/**
* thus, rather than implementing each and every
* instantiation of the product class as follows:
*/

$productConfigs = array(‘type’=>’shirt’,’size’=>’XL’,’color’=>’red’);
$product = new product();
$product->setType($productConfigs[‘type’]);
$product->setSize($productConfigs[‘size’]);
$product->setColor($productConfigs[‘color’]);

/**
* and then having to change every instantiation
* if/when the product class changes!
* instead, we create a productBuilder,
* and then the change simply happens in the product class
* and in the builder build method
*/

class productBuilder
{
protected $_product = NULL;
protected $_xml = 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;
}
}

/**
* implemented, instead as follows:
*/

$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

Comments are closed.