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文件
posted @ 2020-12-31 13:50  linsonga  阅读(55)  评论(0编辑  收藏  举报