建造者

/**
 * @author  v.r  And  
 * 
 * @example
 * 建造者
 * 建造者设计模式定义了处理其他对象的复杂构建对象设计    
 * 列子:
 *  以商品为列子
 * 
 * @copyright copyright information
 * 
 */

$productCofigs = array(
	'type'=>'shirt',
	'size'=>'xl',
	'color'=>'red',
);

class Product
{
	
	protected $type = '';
	protected $size = '';
	protected $color = '';

	public function setType ($type) 
	{
		$this->type = $type;
	}

	public function setColor ($color) 
	{
		$this->color = $color;
	}

	public function setSize ($size)
	{
		$this->size = $size;
	}

}

//创建商品对象

//$Product = new  Product();
//$Product->setType($productCofigs['type']);
//$product->setColor($productCofigs['color']);
//$product->setSize($productCofigs['size']);

/**
 * 以上是创建一商品对象时候的操作
 * 问题:
 *   创建对象时候分别调用每个方法是不是必要的合适的呢?
 *   如果不分别调用我们应该选取什么方式来做呢?
 *   建造模式是否能解决问题以上顾虑
 */

class ProductBuilder
{
	protected $product = NULL;
	protected $configs = array();

	public function __construct($configs)
	{
		$this->product = new  Product();
		$this->configs = $configs;
	}

	//构建
	public function build() 
	{
		$this->product->setSize($this->configs['size']);
		$this->product->setType($this->configs['type']);
		$this->product->setColor($this->configs['color']);
	}
    
    public function getProduct() 
    {
    	return $this->product;
    }
}

/**
* build() 方法隐藏product对象的实际方法调用
* 如果product类以后会发生改变,只是需要修改build()方法
*
*/

$builder =  new ProductBuilder($productCofigs);
$builder->build();
$product =  $builder->getProduct();
var_dump($product);

/**
 * 建造者模式最主的目的是消除其他对象的复杂创建过程,
 * 而且在某个对象进行构造和配置方法时可以尽可以能地减少重复更改代码
 */


转载于:https://my.oschina.net/u/1246814/blog/512321

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值