2009-05-08 :-)
_ 仕事
休み
_ [デザインパターン][Adapter]Head First デザインパターンを写経する - 7章 Adapter パターン
#!/usr/bin/ruby -Ks
module Duck
  def quack
  end
  def fly
  end
end
class MallardDuck
  include Duck
  def quack
    puts "ガーガー"
  end
  def fly
    puts "飛んでいます"
  end
end
module Turkey
  def gobble
  end
  def fly
  end
end
class WildTurkey
  include Turkey
  def gobble
    puts "ゴロゴロ"
  end
  def fly
    puts "短い距離を飛んでいます"
  end
end
class TurkeyAdapter
  include Duck
  def initialize( turkey )
    @turkey = turkey
  end
  def quack
    @turkey.gobble
  end
  def fly
    5.times do
      @turkey.fly
    end
  end
end
def main
  duck = MallardDuck.new
  turkey = WildTurkey.new
  turkeyAdapter = TurkeyAdapter.new( turkey )
  puts "Turky の出力..."
  turkey.gobble
  turkey.fly
  puts "\nDuck の出力..."
  testDuck( duck )
  puts "\nTurkeyAdapter の出力..."
  testDuck( turkeyAdapter )
end
def testDuck( duck )
  duck.quack
  duck.fly
end
main
% ./duck.rb Turky の出力... ゴロゴロ 短い距離を飛んでいます Duck の出力... ガーガー 飛んでいます TurkeyAdapter の出力... ゴロゴロ 短い距離を飛んでいます 短い距離を飛んでいます 短い距離を飛んでいます 短い距離を飛んでいます 短い距離を飛んでいます
_ [デザインパターン][Template Method]Head First デザインパターンを写経する - 8章 Template Method パターン
#!/usr/bin/ruby -Ks
class CaffeineBeverage
  def prepareRecipe
    boilWater
    brew
    pourInCup
    addCondiments
  end
  def brew
  end
  def addCondiments
  end
  def boilWater
    puts "お湯を沸かします"
  end
  def pourInCup
    puts "カップに注ぎます"
  end
end
class Tea < CaffeineBeverage
  def brew
    puts "紅茶を浸します"
  end
  def addCondiments
    puts "レモンを追加します"
  end
end
class Coffee < CaffeineBeverage
  def brew
    puts "フィルタでコーヒーをドリップします"
  end
  def addCondiments
    puts "砂糖とミルクを追加します"
  end
end
def main
  tea = Tea.new
  coffee = Coffee.new
  puts "\n紅茶を作っています..."
  tea.prepareRecipe
  puts "\nコーヒーを作っています..."
  coffee.prepareRecipe
end
main
% ./beverage.rb 紅茶を作っています... お湯を沸かします 紅茶を浸します カップに注ぎます レモンを追加します コーヒーを作っています... お湯を沸かします フィルタでコーヒーをドリップします カップに注ぎます 砂糖とミルクを追加します
[ツッコミを入れる]










