Builder パターン

id:hyuki さんのデザインパターン本から Prototype パターンを移植してみます。

#!/usr/local/bin/ruby

class Director
  def initialize(builder)
    @builder = builder
  end

  def construct
    @builder.make_title("Greeting")
    @builder.make_string("朝から昼にかけて")
    @builder.make_items("おはようございます", "こんにちは")
    @builder.make_string("夜に")
    @builder.make_items("こんばんは", "おやすみなさい", "さようなら。")
    @builder.close
  end
end

class TextBuilder
  def initialize
    @text = String.new
  end
  
  def make_title(title)
    @text += "=========================================?n"
    @text += "『#{title}』?n?n"
  end

  def make_string(str)
    @text += "■ #{str}?n?n"
  end

  def make_items(*items)
    items.each do |item|
      @text += "  ・#{item}?n"
    end
  end

  def close
    @text += "=========================================?n"
  end

  def result
    @text
  end
end

builder = TextBuilder.new
Director.new(builder).construct
puts builder.result

実行結果は、

=========================================
『Greeting』

■ 朝から昼にかけて

  ・おはようございます
  ・こんにちは
■ 夜に

  ・こんばんは
  ・おやすみなさい
  ・さようなら。
=========================================

となりました。新しく実践したことと言えば make_items(*items) として引数を配列で受け取っているところぐらいです。

今回もインタフェースや抽象クラス抜きです。HTMLBuilder を追加するときはダックタイピングです。Ruby っぽくするアイデアは特に思いつきませんでした。