PHP设计模式之:建造者模式

建造者模式:

将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示的设计模式;

目的

消除其他对象复杂的创建过程

结构图:

PHP设计模式之:建造者模式

优点:

建造者模式可以很好的将一个对象的实现与相关的业务逻辑分离开来,从而可以在不改变事件逻辑的前提下,使增加(或改变)实现变得非常容易

缺点:

建造者接口的修改会导致所有执行类的修改。

以下情况应当使用建造者模式:

1、 需要生成的产品对象有复杂的内部结构。
2、 需要生成的产品对象的属性相互依赖,建造者模式可以强迫生成顺序。
3、 在对象创建过程中会使用到系统中的一些其它对象,这些对象在产品对象的创建过 程中不易得到。

使用建造者模式主要有以下效果:
1、 建造者模式的使用使得产品的内部表象可以独立的变化。使用建造者模式可以使客 户端不必知道产品内部组成的细节。
2、 每一个Builder都相对独立,而与其它的Builder无关。
3、 模式所建造的最终产品更易于控制。

代码实现:

 

<?php

/1**

 建造者模式

 将一个复杂对象的构造与它的表示分离,是同样的构建过程可以创建不同的表示;

 目的是为了消除其他对象复杂的创建过程

 */

 

/1**

 产品,包含产品类型、价钱、颜色属性

 */

class Product

{

public $_type  null;

public $_price null;

public $_color null;

 

public function setType($type)

{

echo 'set the type of the product,';

$this->_type $type;

}

 

public function setPrice($price)

{

echo 'set the price of the product,';

$this->_price $price;

}

 

public function setColor($color)

{

echo 'set the color of the product,';

$this->_color $color;

}

}

 

$config array(

'type'  => 'shirt',

'price' => 100,

'color' => 'red',

);

 

//不使用builder模式

$product new Product();

$product->setType($config['type']);

$product->setPrice($config['price']);

$product->setColor($config['color']);

 

//使用builder模式

/1**

 builder类

 */

class ProductBuilder

{

public $_config null;

public $_object null;

 

public function ProductBuilder($config)

{

$this->_object new Product();

$this->_config $config;

}

 

public function build()

{

echo '<br />Using builder pattern:<br />';

$this->_object->setType($this->_config['type']);

$this->_object->setPrice($this->_config['price']);

$this->_object->setColor($this->_config['color']);

}

 

public function getProduct()

{

return $this->_object;

}

}

 

$objBuilder new ProductBuilder($config);

$objBuilder->build();

$objProduct $objBuilder->getProduct();

echo '<br />';

var_dump($objProduct);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值