🦁

ダックタイピング

に公開

動的型付け言語のダックタイピング

Pythonのリファレンスでは、

ダック・タイピングは「あるオブジェクトが正しいインタフェースを持っているかどうかを決定するた>めに、オブジェクトの型を見ることはしないプログラミングスタイルである」

と説明されている。

一言でいうと、それがアヒルの鳴き声なら、アヒルとみなすことである。
実際アヒルかどうか関係はない。

という考え方である。
なお、この手法は、動的型付け言語onlyである。

実際のコード

抽象的なShapeクラス(Rubyにはabstractがないから、自分で例外にする)

module Shape
  def area
    raise NotImplementedError, "areaメソッドを実装してね!"
  end
end

Rectangleクラス(Shapeを継承)

class Rectangle
  include Shape
  def initialize(length, width)
    @length = length
    @width = width
  end

  def area
    @length * @width
  end
end

Squareクラス(Shapeを継承)

class Square
  include Shape
  def initialize(side)
    @side = side
  end

  def area
    @side * @side
  end
end

Boxクラス(Shapeを中に持つ → Composition!)

class Box
  def initialize(shape)
    @shape = shape
  end

  def area
    @shape.area  # ← 委譲
  end
end

実行例

box1 = Box.new(Rectangle.new(10, 5))
box2 = Box.new(Square.new(4))

puts box1.area  # => 50
puts box2.area  # => 16

呼び出し時、Rectangle.newや、Square.newがareaを持っているなら、それを発動されることができる。
まさに、マジックである。

Discussion