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

yipeiwu_com6年前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();

相关文章

PHP编程求最大公约数与最小公倍数的方法示例

本文实例讲述了PHP编程求最大公约数与最小公倍数的方法。分享给大家供大家参考,具体如下: //求最大公约数 function max_divisor($a,$b) { $n =...

PHP7新功能总结

以下是小编给大家整理的关于PHP7的相关更新内容和知识点。 新功能 PHP 7增加了许多特性,其中最重要的特性如下所述 • 性能改进——在PHP7中合并了PHPNG代码,速度...

PHP一些常用的正则表达式字符的一些转换

匹配双字节字符(包括汉字在内): [^\x00-\xff]    应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)  String.pr...

php实现基于PDO的预处理示例

本文实例讲述了php实现基于PDO的预处理。分享给大家供大家参考,具体如下: $servername="localhost"; $username="root"; $password...

mac os快速切换多个PHP版本的方法

php是为了快速构建一个web页面而迅速被大家广为接受的开源语言,通过不断发展已经有了很多的php开源系统,满足了目前大部分用户的站点需求。1995年初php诞生到现在已经存在多个版本,...