---
title: "设计模式与动态语言之建造者模式 Builder"
author: "jim.jin"
date: "2010-01-14T12:44:43Z"
tags: ["Ruby", "UML", "工作", "算法", "设计模式"]
categories: ["编程语言"]
slug: "builder"
draft: false
lastmod: "2010-01-14T12:44:55Z"
id: 570010
url: "https://jim-jin.iteye.com/blog/570010"
---

建造者模式是一种比较常用的简单的对象创建型设计模式。
它在软件系统中，主要用于面临着“一个复杂对象”的创建工作，其通常由各个部分的子对象用一定的算法构成；由于需求的变化，这个复杂对象的各个部分经常面临着剧烈的变化，但是将它们组合在一起的算法确相对稳定。

**
意图：将一个复杂的构建与其表示相分离，使得同样的构建过程可以创建不同的表示。**

结构：

![](http://dl.iteye.com/upload/attachment/193261/b5f8810e-1113-30ad-aaf5-fb6f1e709ffb.png)

适用性：

需要生成的产品对象有复杂的内部结构。
需要生成的产品对象的属性相互依赖，建造者模式可以强迫生成顺序。
在对象创建过程中会使用到系统中的一些其它对象，这些对象在产品对象的创建过程中不易得到。



动态性：
此模式在动态性方面没有特别的动态特性。

效果：
建造者模式的使用使得产品的内部表象可以独立的变化。使用建造者模式可以使客户端不必知道产品内部组成的细节；
每一个Builder都相对独立，而与其它的Builder无关；
可使对构造过程更加精细控制；
建造者模式的缺点在于难于应付“分步骤构建算法”的需求变动。


下面是个小例子：


```Ruby


class Director
  def build(builder)
    [:header, :toolbar, :content, :footer].each do |m|
      builder.send("build_#{m}")
    end
  end
end

class BlueWindowBuilder
  def build_header
    BlueHeader.new
  end

  def build_toolbar
    BlueToolbar.new
  end

  def build_content
    BlueContent.new
  end

  def build_footer
    BlueFooter.new
  end
end

class BlueHeader
  def initialize
    @bg = 'Blue'
    @title = 'Blue window'
    puts "Build #{self.class.name}"
  end
end

class BlueToolbar
  def initialize
    @bg = 'light blue'
    @buttons_bg = 'blue'
    puts "Build #{self.class.name}"
  end
end

class BlueContent
  def initialize
    @bg = 'gray'
    puts "Build #{self.class.name}"
  end
end

class BlueFooter
  def initialize
    @font_color = 'white'
    puts "Build #{self.class.name}"
  end
end

class GrayWindowBuilder
  def build_header
    GrayHeader.new
  end

  def build_toolbar
    GrayToolbar.new
  end

  def build_content
    GrayContent.new
  end

  def build_footer
    GrayFooter.new
  end
end

class GrayHeader
  def initialize
    @bg = 'Gray'
    @title = 'Gray window'
    puts "Build #{self.class.name}"
  end
end

class GrayToolbar
  def initialize
    @bg = 'Black'
    @buttons_bg = 'gray'
    puts "Build #{self.class.name}"
  end
end

class GrayContent
  def initialize
    @bg = 'white'
    puts "Build #{self.class.name}"
  end
end

class GrayFooter
  def initialize
    @font_color = 'black'
    puts "Build #{self.class.name}"
  end
end

dir = Director.new
puts "\nBuilding blue window ...\n"
dir.build(BlueWindowBuilder.new)
puts "\nBuild Gray window ...\n"
dir.build(GrayWindowBuilder.new)

```


类图：

![](http://dl.iteye.com/upload/attachment/193379/c43ccce7-d2f0-31bd-afd3-1a20dae90601.jpg)


[点击下载UML及源码](http://dl.iteye.com/topics/download/ac38c16f-afee-374d-82f1-09cad93f8a77)