php设计模式 Builder(建造者模式)

前端之家收集整理的这篇文章主要介绍了php设计模式 Builder(建造者模式)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

<div class="codetitle"><a style="CURSOR: pointer" data="62778" class="copybut" id="copybut62778" onclick="doCopy('code62778')"> 代码如下:

<div class="codebody" id="code62778">
<?PHP
/*
建造者模式

将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示
*/
class Product
{
public $_type = null;
public $_size = null;
public $_color = null; public function setType($type)
{
echo "set product type
";
$this->_type = $type;
} public function setSize($size)
{
echo "set product size
";
$this->_size = $size;
} public function setColor($color)
{
echo "set product color
";
$this->_color = $color;
}
} $config = array(
"type"=>"shirt",
"size"=>"xl",
"color"=>"red",
); // 没有使用bulider以前的处理
$oProduct = new Product();
$oProduct->setType($config['type']);
$oProduct->setSize($config['size']);
$oProduct->setColor($config['color']);
// 创建一个builder类
class ProductBuilder
{
var $_config = null;
var $_object = null; public function ProductBuilder($config)
{
$this->_object = new Product();
$this->_config = $config;
} public function build()
{
echo "--- in builder---
";
$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 = new ProductBuilder($config);
$objBuilder->build();
$objProduct = $objBuilder->getProduct();

猜你在找的PHP相关文章