欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-01-30 17:31:40
复制代码 代码如下:
复制代码 代码如下:

<?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();