建造者模式又名生成器模式,是一種對象構建模式。它能夠將複雜對象的建造過程抽象出來(抽象類別),使這個抽象過程的不一樣實現方法能夠構造出不一樣表現(屬性)的對象。php
建造者模式是一步一步建立一個複雜的對象,它容許用戶只經過指定複雜對象的類型和內容就能夠構建它們,用戶不須要知道內部的具體構建細節。例如,一輛汽車由輪子,發動機以及其餘零件組成,對於普通人而言,咱們使用的只是一輛完整的車,這時,咱們須要加入一個構造者,讓他幫咱們把這些組件按序組裝成爲一輛完整的車。學習
包含定義組成部件的類,包括將這些部件裝配成最終產品的接口。ui
<?php /** * chouxiang builer */ abstract class Builder { protected $car; abstract public function buildPartA(); abstract public function buildPartB(); abstract public function buildPartC(); abstract public function getResult(); } class CarBuilder extends Builder { function __construct() { $this->car = new Car(); } public function buildPartA(){ $this->car->setPartA('發動機'); } public function buildPartB(){ $this->car->setPartB('輪子'); } public function buildPartC(){ $this->car->setPartC('其餘零件'); } public function getResult(){ return $this->car; } } class Car { protected $partA; protected $partB; protected $partC; public function setPartA($str){ $this->partA = $str; } public function setPartB($str){ $this->partB = $str; } public function setPartC($str){ $this->partC = $str; } public function show() { echo "這輛車由:".$this->partA.','.$this->partB.',和'.$this->partC.'組成'; } } class Director { public $myBuilder; public function startBuild() { $this->myBuilder->buildPartA(); $this->myBuilder->buildPartB(); $this->myBuilder->buildPartC(); return $this->myBuilder->getResult(); } public function setBuilder(Builder $builder) { $this->myBuilder = $builder; } } $carBuilder = new CarBuilder(); $director = new Director(); $director->setBuilder($carBuilder); $newCar = $director->startBuild(); $newCar->show(); ?>
以上是文章所有內容,有須要學習交流的友人請加入交流羣的我們一塊兒,有問題一塊兒交流,一塊兒進步!前提是你是學技術的。感謝閱讀!this
點此加入該羣spa