mugyu
1/21/2016 - 12:34 AM

ダブルディスパッチ double dispatch

ダブルディスパッチ double dispatch

ダブルディスパッチ double dispatch

class Base
  attr_reader :data
  def initialize(data)
    @data = data
  end

  def caliculate(other)
    other.caliculate(self)
  end
end

class Plus < Base
  def caliculate(other)
    p other.data + @data
  end
end

class Minus < Base
  def caliculate(other)
    p other.data - @data
  end
end

class Multi < Base
  def caliculate(other)
    p other.data * @data
  end
end

base = Base.new(7)

plus = Plus.new(3)
multi = Multi.new(2)
minus = Minus.new(4)

# パラメータのクラスに対応して、それぞれの処理がなされる
base.caliculate(plus)   #=> 10
base.caliculate(multi)  #=> 14
base.caliculate(minus)  #=> 3