您的位置:首页 > 编程语言 > PHP开发

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

2013-12-20 14:28 423 查看

建造者模式:

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

目的:

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

结构图:

优点:

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

缺点:

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

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

1、 需要生成的产品对象有复杂的内部结构。

2、 需要生成的产品对象的属性相互依赖,建造者模式可以强迫生成顺序。

3、 在对象创建过程中会使用到系统中的一些其它对象,这些对象在产品对象的创建过

程中不易得到。

使用建造者模式主要有以下效果:

1、 建造者模式的使用使得产品的内部表象可以独立的变化。使用建造者模式可以使客

户端不必知道产品内部组成的细节。

2、 每一个Builder都相对独立,而与其它的Builder无关。

3、 模式所建造的最终产品更易于控制。

代码实现:

/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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: