1. 程式人生 > 實用技巧 >php 設計模式之 建造者

php 設計模式之 建造者



1. 建造者模式

將一個複雜物件的構建與它的表示分離,使得同樣的構建過程可以建立不同的表示


2. 實列

class Product {   // (商品)產品類
    private $parts = [];

    public function Add(String $part): void {
        $this->parts[] = $part;
    }

    public function Show(): void {
        echo PHP_EOL . '產品建立 ----', PHP_EOL;
        foreach ($this->parts as $part) {
            echo $part, PHP_EOL;
        }
    }
}

interface Builder {    // (工廠)建造者介面,有不同工廠的貨物並加工
    public function BuildPartA(): void;
    public function BuildPartB(): void;
    public function GetResult(): Product;
}

class ConcreteBuilder1 implements Builder {   // 貨物1
    private $product;

    public function __construct()
    {
        $this->product = new Product();
    }

    public function BuildPartA(): void
    {
        $this->product->Add('部件A');
    }
    public function BuildPartB(): void
    {
        $this->product->Add('部件B');
    }
    public function GetResult(): Product
    {
        return $this->product;
    }
}

class ConcreteBuilder2 implements Builder {   // 貨物2
    private $product;

    public function __construct() {
        $this->product = new Product();
    }

    public function BuildPartA(): void {
        $this->product->Add('部件X');
    }
    public function BuildPartB(): void {
        $this->product->Add('部件Y');
    }
    public function GetResult(): Product {
        return $this->product;
    }
}


class Director {   // (工人)施工隊,選擇不同工廠貨物,生產產品
    public function Construct(Builder $builder) {
        $builder->BuildPartA();
        $builder->BuildPartB();
    }
}


$director = new Director();
$b1 = new ConcreteBuilder1();
$b2 = new ConcreteBuilder2();

$director->Construct($b1);
$p1 = $b1->getResult();
$p1->Show();

$director->Construct($b2);
$p2 = $b2->getResult();
$p2->Show();



3. 使用場景

  1. Laravel 資料庫元件使用建造者模式,原始碼Database\Eloquent和Database\Query目錄中有Builder.php檔案