<?php
// 建造者模式
class Product
{
private $size;
private $color;
private $type;
public function setSize($size) {
$this->size = $size;
}
public function setColor($color) {
$this->color = $color;
}
public function setType($type) {
$this->type = $type;
}
public function toString() {
ob_start();
echo 'Size: ', $this->size , '<br/>';
echo 'Color: ', $this->color , '<br/>';
echo 'Type: ', $this->type , '<br/>';
return ob_get_clean();
}
}
// 分别调用每个方法并不是最佳的做法
$product = new Product();
$product->setSize(100);
$product->setColor('red');
$product->setType('shirt');
// echo $product;
// -----------------------------------------------------------
/**
* 建造者模式
* 将一个复杂对象的构建与它的表示分离,使同样的构建过程可以创建不同的表示
*/
class ProductBuilder
{
private $product;
private $configs;
public function construct($cfgs) {
$this->configs = $cfgs;
$this->product = new Product();
}
/**
* 构建对象
*/
public function buildProduct() {
$this->product->setSize($this->configs['size']);
$this->product->setColor($this->configs['color']);
$this->product->setType($this->configs['type']);
}
public function getProduct() {
return $this->product;
}
}
$cfgs = array('size'=>100,'color'=>'blue','type'=>'shirt');
$builder = new ProductBuilder($cfgs);
$builder->buildProduct();
echo $builder->getProduct();以上就是PHP建造者模式代码示例详解的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号