// 产品类
class Product {
private $parts = [];
public function addPart($part) {
$this->parts[] = $part;
}
public function listParts() {
echo "Product parts: " . implode(', ', $this->parts) . "\n";
}
}
// 抽象生成器接口
interface Builder {
public function buildPart1();
public function buildPart2();
public function getResult(): Product;
}
// 具体生成器1
class ConcreteBuilder1 implements Builder {
private $product;
public function __construct() {
$this->reset();
}
public function reset() {
$this->product = new Product();
}
public function buildPart1() {
$this->product->addPart("Part1A");
}
public function buildPart2() {
$this->product->addPart("Part2A");
}
public function getResult(): Product {
$result = $this->product;
$this->reset();
return $result;
}
}
// 具体生成器2
class ConcreteBuilder2 implements Builder {
private $product;
public function __construct() {
$this->reset();
}
public function reset() {
$this->product = new Product();
}
public function buildPart1() {
$this->product->addPart("Part1B");
}
public function buildPart2() {
$this->product->addPart("Part2B");
}
public function getResult(): Product {
$result = $this->product;
$this->reset();
return $result;
}
}
// 指挥者
class Director {
public function buildMinimalProduct(Builder $builder) {
$builder->buildPart1();
}
public function buildFullFeaturedProduct(Builder $builder) {
$builder->buildPart1();
$builder->buildPart2();
}
}
// 客户端代码
$director = new Director();
$builder1 = new ConcreteBuilder1();
$director->buildMinimalProduct($builder1);
$product1 = $builder1->getResult();
$product1->listParts();
$builder2 = new ConcreteBuilder2();
$director->buildFullFeaturedProduct($builder2);
$product2 = $builder2->getResult();
$product2->listParts();
在这个例子中,Director 是负责指导构建过程的类,而 ConcreteBuilder1 和 ConcreteBuilder2 分别是具体的生成器。Product 是最终生成的产品,它包含多个组件。
客户端可以通过选择不同的生成器来构建不同类型的产品,而不必关心产品是如何逐步构建的。这种方式下,可以在不同的上下文中使用相同的生成器构建不同的产品。
转载请注明出处:http://www.pingtaimeng.com/article/detail/11932/PHP