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

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

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

相关文章

探讨多键值cookie(php中cookie存取数组)的详解

cookie默认不能存数组,所以下面的写法是错误的。报错如下:Warning: setcookie() expects parameter 2 to be string, array g...

PHP实现仿百度文库,豆丁在线文档效果(word,excel,ppt转flash)

本文实例讲述了PHP实现仿百度文库,豆丁在线文档效果。分享给大家供大家参考,具体如下: 由于项目要实现类似百度文库的功能,又是我一个人做的项目,所以就想到找免费的现成的来使用。在网上找到...

PHP使用HTML5 FileApi实现Ajax上传文件功能示例

PHP使用HTML5 FileApi实现Ajax上传文件功能示例

本文实例讲述了PHP使用HTML5 FileApi实现Ajax上传文件功能。分享给大家供大家参考,具体如下: FileApi是HTML5的一个新特性,有了这个新特性,js就可以读取本地的...

php实现三级级联下拉框

这是我在网上查找到的php实现三级级联下拉框的资料,共享个大家,大家一起进步,具体内容如下 index.php: <html> <head> <met...

PHP Zip压缩 在线对文件进行压缩的函数

复制代码 代码如下: /* creates a compressed zip file */ function create_zip($files = array(),$destinat...