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

php有23种设计模式,你全都知道吗?下面用代码介绍建造者模式(Builder模式)<?php

/**

* 建造者模式

*

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

*/

class Product {

public $_type = null;

public $_size = null;

public $_color = null;

public function setType($type) {

echo "set product type
";

$this->_type = $type;

}

public function setSize($size) {

echo "set product size
";

$this->_size = $size;

}

public function setColor($color) {

echo "set product color
";

$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---
";

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

其他相关设计模式:

转载随意,但请附上文章地址:-)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值