<?php class Product { private $_parts = array(); public function add(string $part) { $this->_parts[] = $part; } public function show() { echo "\n PRODUCT CREATEING...<br/>"; foreach ($this->_parts as $part) { echo $part; echo "<br/>"; } } } abstract class Builder { abstract function build_part_A(); abstract function build_part_B(); abstract function get_result(): Product; } class Concrete_builder_one extends Builder { private $_product = null; public function __construct() { $this->_product = new Product(); } public function build_part_A() { $this->_product->add(‘PART A‘); } public function build_part_B() { $this->_product->add(‘PART B‘); } public function get_result() : Product { return $this->_product; } } class Concrete_builder_two extends Builder { private $_product = null; public function __construct() { $this->_product = new Product(); } public function build_part_A() { $this->_product->add(‘PART X‘); } public function build_part_B() { $this->_product->add(‘PART Y‘); } public function get_result() : Product { return $this->_product; } } class Director { public function concrete(Builder $builder) { $builder->build_part_A(); $builder->build_part_B(); } } //CLIENT CODE $director = new Director(); $b1 = new Concrete_builder_one(); $b2 = new Concrete_builder_two(); $director->concrete($b1); $product1 = $b1->get_result(); $product1->show(); $director->concrete($b2); $product2 = $b2->get_result(); $product2->show();
建造者模式:
将一个复杂对象的构建与它的表示分离,使得同样的建造过程可以创建不同的表示。
如果我们用了建造者模式,那么用户就只需要指定需要建造的类型就可以得到它们,而具体建造的过程和细节就不需要知道了。
Director,指挥者,它是构建一个使用Builder接口的对象。在Director中完成部件的装配(即建造过程)!!
时间: 2024-09-28 17:53:25