当前位置: 移动技术网 > IT编程>开发语言>PHP > php设计模式 Builder(建造者模式)

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

2019年04月21日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

<?php
/**
* 建造者模式
*
* 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示
*/
class product
{
public $_type = null;
public $_size = null;
public $_color = null;

public function settype($type)
{
echo "set product type<br/>";
$this->_type = $type;
}

public function setsize($size)
{
echo "set product size<br/>";
$this->_size = $size;
}

public function setcolor($color)
{
echo "set product color<br/>";
$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---<br/>";
$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();

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网