建造者模式

建造者模式（英：Builder Pattern），也译为生成器模式，是一种对象构建设计模式。它可以将复杂对象的建造过程抽象出来（抽象类别），使这个抽象过程的不同实现方法可以构造出不同表现（属性）的对象。
适用性.
在以下情况使用建造者模式：
结构.
在上面的UML类图中，codice_1类不直接的创建并组装codice_2和codice_3对象。codice_1转而提及codice_5接口来建造（创建并组装）一个复杂对象的各部份，这使得codice_1独立于哪个具体类要被初始化（哪个表示要被创建）。codice_7类通过创建并组装codice_2和codice_3对象来实现codice_5接口。
UML序列图展示了运行时交互：codice_1对象调用codice_12于codice_7对象之上，它创建并组装codice_2对象。此后，codice_1调用codice_16于codice_7之上，它创建并组装codice_3对象。
协作.
客户创建Director对象，并用它所想要的Builder对象进行配置。
范例.
Java.
Java例子：
/** "Product" */
class Pizza {
 private String dough = "";
 private String sauce = "";
 private String topping = "";
 
/** "Abstract Builder" */
abstract class PizzaBuilder {
 protected Pizza pizza;
 public abstract void buildDough();
 public abstract void buildSauce();
 public abstract void buildTopping();
 
/** "ConcreteBuilder" */
class HawaiianPizzaBuilder extends PizzaBuilder {
 
/** "ConcreteBuilder" */
class SpicyPizzaBuilder extends PizzaBuilder {
 
 /** "Director" */
class Waiter {
 private PizzaBuilder pizzaBuilder;
 public void constructPizza() {
 pizzaBuilder.createNewPizzaProduct();
 pizzaBuilder.buildDough();
 pizzaBuilder.buildSauce();
 pizzaBuilder.buildTopping();
/** A customer ordering a pizza. */
class BuilderExample {
 public static void main(String[] args) {
 Waiter waiter = new Waiter();
 PizzaBuilder hawaiianPizzabuilder = new HawaiianPizzaBuilder();
 PizzaBuilder spicyPizzabuilder = new SpicyPizzaBuilder();
 waiter.setPizzaBuilder ( hawaiianPizzabuilder );
 waiter.constructPizza();
 Pizza pizza = waiter.getPizza();
C#.
C#例子：
// Represents a product created by the builder.
public class Bicycle {
 public Bicycle(string maker, string model, string colour, int height) {
 Maker = maker;
 Model = model;
 Colour = colour;
 Height = height;
// The builder abstraction.
public interface IBicycleBuilder {
 Bicycle GetResult();
// Concrete builder implementation.
public class GTBicyclesBuilder : IBicycleBuilder {
 public Bicycle GetResult() {
 return Height == 29 ? new Bicycle("GT Bicycles Inc.", "Avalanche", Colour, Height) : null;
// The director.
public class MountainBikeBuildDirector {
 private IBicycleBuilder _builder;
 public MountainBikeBuildDirector(IBicycleBuilder builder) {
 _builder = builder;
 public void Construct() {
 _builder.Colour = "Red";
 _builder.Height = 29;
 public Bicycle GetResult() {
 return this._builder.GetResult();
public class Client {
 public void DoSomethingWithBicycles() {
 var director = new MountainBikeBuildDirector(new GTBicyclesBuilder());
 // Director controls the stepwise creation of product and returns the result.
 director.Construct();
 Bicycle myMountainBike = director.GetResult();
Python.
Python的例子：
from abc import ABC, abstractmethod
from weakref import WeakKeyDictionary
class Component():
 def __init__(self, name, **kwargs):
 self.name = name
 self.weakref_dict = WeakKeyDictionary()
 def __get__(self, obj, objtype=None):
 return (self.weakref_dict[obj]
 if obj in self.weakref_dict else None)
 def __set__(self, obj, value):
 self.weakref_dict[obj] = {'name': self.name} | value
class Product():
 part_A = Component('part_A')
 part_B = Component('part_B')
 def __init__(self, **kwargs): pass
 @property
 def description(self):
 print(f'Product: {self.part_A['name']}, {self.part_A['builder']}; '
 + f'{self.part_B['name']}, {self.part_B['builder']}.')
class Builder(ABC):
 def __init__(self, **kwargs):
 self.product = Product()
 @abstractmethod
 def build_part_A(self): pass
 @abstractmethod
 def build_part_B(self): pass
 def get_result(self):
 result, self.product = self.product, None
 return result
class BuilderA(Builder):
 def build_part_A(self, **kwargs): 
 self.product.part_A = type(self).params | kwargs
 def build_part_B(self, **kwargs):
 self.product.part_B = type(self).params | kwargs
class BuilderB(Builder):
 def build_part_A(self, **kwargs): 
 self.product.part_A = type(self).params | kwargs
 def build_part_B(self, **kwargs):
 self.product.part_B = type(self).params | kwargs
class Director():
 def __init__(self, builder_cls, **kwargs):
 self.builder_cls = builder_cls
 def __call__(self, **kwargs):
 self.builder = self.builder_cls()
 self.builder.build_part_A(kw=")
 self.builder.build_part_B(kw=")
 result, self.builder = self.builder.get_result(), None
 return result
其执行：
»&gt; product1 = Director(BuilderA)()
»&gt; product1.description
Product: part_A, BuilderA; part_B, BuilderA.
»&gt; product2 = Director(BuilderB)()
»&gt; product2.description
Product: part_A, BuilderB; part_B, BuilderB.
PHP.
PHP例子：
&lt;?php
//设计模式：生成器模式
interface Builder {
 function buildPartA(); //创建部件A比如创建汽车车轮
 //创建部件B 比如创建汽车方向盘
 function buildPartB(); 
 //创建部件C 比如创建汽车发动机
 function buildPartC(); 
 //返回最后组装成品结果 (返回最后装配好的汽车)
 //成品的组装过程不在这里进行,而是转移到下面的Director类中进行.
 //从而实现了解耦过程和部件
 //return Product
 function getResult(); 
class Director {
 private $builder; 
 public function __construct($builder ) { 
 $this-&gt;builder = $builder; 
 // 将部件partA partB partC最后组成复杂对象
 //这里是将车轮、方向盘和发动机组装成汽车的过程
 public function construct() {
 $this-&gt;builder-&gt;buildPartA();
 $this-&gt;builder-&gt;buildPartB();
 $this-&gt;builder-&gt;buildPartC();
class ConcreteBuilder implements Builder {
 public $partA, $partB, $partC;
 public function buildPartA() {
 echo 'partA is builded' . "\n";
 public function buildPartB() {
 echo 'partB is builded' . "\n";
 public function buildPartC() {
 echo 'partC is builded' . "\n";
 public function getResult () {
 echo 'Return product.' . "\n";
 return 1;
$builder = new ConcreteBuilder();
$director = new Director( $builder ); 
$director-&gt;construct(); 
$product = $builder-&gt;getResult(); 
相关模式.
抽象工厂模式与建造者相似，因为它也可以创建复杂对象。主要的区别是建造者模式着重于一步步构造一个复杂对象。而抽象工厂模式着重于多个系列的产品对象（简单的或是复杂的）。建造者在最后的一步返回产品，而对于抽象工厂来说，产品是立即返回的。
合成模式通常是用建造者生成的。