Detailed explanation of PHP builder pattern code examples

黄舟
Release: 2023-03-06 16:56:01
Original
1805 people have browsed it

PHPBuilder PatternDetailed code examples

<?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 &#39;Size: &#39;, $this->size , &#39;<br/>&#39;;
		echo &#39;Color: &#39;, $this->color , &#39;<br/>&#39;;
		echo &#39;Type: &#39;, $this->type , &#39;<br/>&#39;;
		return ob_get_clean();
	}
}

// 分别调用每个方法并不是最佳的做法
$product = new Product();

$product->setSize(100);
$product->setColor(&#39;red&#39;);
$product->setType(&#39;shirt&#39;);
// 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[&#39;size&#39;]);
		$this->product->setColor($this->configs[&#39;color&#39;]);
		$this->product->setType($this->configs[&#39;type&#39;]);
	}

	public function getProduct() {
		return $this->product;
	}
}

$cfgs = array(&#39;size&#39;=>100,&#39;color&#39;=>&#39;blue&#39;,&#39;type&#39;=>&#39;shirt&#39;);
$builder = new ProductBuilder($cfgs);
$builder->buildProduct();
echo $builder->getProduct();
Copy after login

The above is the detailed content of Detailed explanation of PHP builder pattern code examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!