建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
/** * 产品类,定义产品各部件 * Class Product */ class Product { /** * 名称 */ public $name; /** * 尺寸 */ public $size; /** * 颜色 */ public $colour; /** * 产品展示 */ public function show() { echo "产品名称:{$this->name}<br/>产品尺寸:{$this->size}<br/>产品颜色:{$this->colour}"; } } /** * 抽象建造者类,定义产品各部件的抽象方法 */ abstract class Builder { public $product; public function __construct() { $this->product = new Product(); } abstract public function name(); abstract public function size(); abstract public function colour(); abstract public function getProduct(); } /** * 具体建造者类A * Class ConcreteBuilderA */ class ConcreteBuilderA extends Builder { public function name() { // TODO: Implement name() method. $this->product->name = '产品A'; } public function size() { // TODO: Implement size() method. $this->product->size = '20'; } public function colour() { // TODO: Implement colour() method. $this->product->colour = '白色'; } public function getProduct() { // TODO: Implement getProduct() method. return $this->product; } } /** * 具体建造者类B * Class ConcreteBuilderB */ class ConcreteBuilderB extends Builder { public function name() { // TODO: Implement name() method. $this->product->name = '产品B'; } public function size() { // TODO: Implement size() method. $this->product->size = '30'; } public function colour() { // TODO: Implement colour() method. $this->product->colour = '黑色'; } public function getProduct() { // TODO: Implement getProduct() method. return $this->product; } } /** * 指挥者 * Class Director */ class Director { /** * 指挥构造过程 * @param Builder $builder */ public function construct(Builder $builder) { $builder->name(); $builder->size(); $builder->colour(); return $builder->getProduct(); } } // 客户端调用 // 指挥者 $director = new Director(); // 产品A建造 $productA = new ConcreteBuilderA(); $directorA = $director->construct($productA); $directorA->show(); echo "<br/>--------------------------------<br/>"; // 产品B建造 $productB = new ConcreteBuilderB(); $directorB = $director->construct($productB); $directorB->show(); // 结果 产品名称:产品A 产品尺寸:20 产品颜色:白色 -------------------------------- 产品名称:产品B 产品尺寸:30 产品颜色:黑色