📅  最后修改于: 2023-12-03 15:25:32.917000             🧑  作者: Mango
建造者设计模式(Builder Design Pattern)是一种创建型设计模式,它允许你将复杂对象的构建过程从其表示中分离出来,以便同样的构建过程可以创建不同的表示。
建造者设计模式包含以下角色:
以下是模式结构图:
Product
类表示被构建的复杂对象,它包含多个部件。Builder
接口,声明用于建造不同部件的方法。ConcreteBuilder
类,实现 Builder
接口并构建和装配各个部件。Director
类,负责控制构建过程,即指导 ConcreteBuilder
如何构建和装配不同的部件。Director
和具体建造者 ConcreteBuilder
类,然后调用 Director
实例的构建方法,即可得到构建完成的产品对象。以下是示例代码,以 PHP 为例:
// Product
class Car
{
private $parts = [];
public function addPart($part)
{
$this->parts[] = $part;
}
public function listParts()
{
return implode(', ', $this->parts);
}
}
// Builder
interface Builder
{
public function addDoors();
public function addEngine();
public function addWheels();
public function getVehicle(): Car;
}
// ConcreteBuilder
class CarBuilder implements Builder
{
private $car;
public function __construct()
{
$this->car = new Car();
}
public function addDoors()
{
$this->car->addPart('4 doors');
}
public function addEngine()
{
$this->car->addPart('V6 engine');
}
public function addWheels()
{
$this->car->addPart('alloy wheels');
}
public function getVehicle(): Car
{
return $this->car;
}
}
// Director
class CarDealer
{
private $builder;
public function __construct(Builder $builder)
{
$this->builder = $builder;
}
public function constructCar()
{
$this->builder->addDoors();
$this->builder->addEngine();
$this->builder->addWheels();
}
}
// Client
$carBuilder = new CarBuilder();
$carDealer = new CarDealer($carBuilder);
$carDealer->constructCar();
$car = $carBuilder->getVehicle();
echo $car->listParts(); // Output: 4 doors, V6 engine, alloy wheels
建造者设计模式适用于以下场景:
Director
和 ConcreteBuilder
的交互顺序来改变对象的内部表示。