---
title: "[转帖]重新认识Ruby的多态和duck type"
author: "biyeah"
date: "2011-12-05T11:56:50Z"
tags: []
categories: ["编程语言"]
slug: "ruby-duck-type"
draft: false
lastmod: "2011-12-05T11:56:50Z"
id: 1292005
url: "https://biyeah.iteye.com/blog/1292005"
---

多态在Java中是如何定义的？
原文：<http://developer.51cto.com/art/200708/54611.htm>

我这样理解：多态需要借助接口来实现，就是所有实现了该特定的接口的类用起来都象他。

什么是duck type？

在Programming Ruby中这样定义：如果对象能够象鸭子那样行走，象鸭子那样呱呱叫，那么解释器会很高兴的把它当做鸭子来对待的。（Programming Ruby 中文版 P367）

一天，我问我一个同事，到底Ruby中有没有多态？

得到一个有趣的答复：弱类型的动态语言，没有抽象类，没有接口，你说有没有多态？

多态很有用，多态是不是只有静态面向对象语言，如Java/C#等才有呢？当然不是了，多态是OO语言的三大特性之一。

而Ruby是纯面向对象的语言，Ruby当然有多态。Ruby的多态特性就是它的duck type。

话不多说，贴代码：


```ruby
class SimpleFilter
  attr_reader :fltr_expres

  def initialize(fltr_expres)
    @fltr_expres = fltr_expres
  end

  def apply_filter(value)
    value.include?(@fltr_expres)
  end
end

class RegexFilter
  attr_reader :fltr_expres

  def initialize(fltr_exprs)
    @fltr_expres = fltr_exprs
  end

  def apply_filter(value)
    value =~ @fltr_expres
  end
end
# SimpleFilter和RegexFilter这两个类并不共享一个基类 
# 在单元测试中对两个类的实例组成的集合进行迭带 
# 简单的调用同名的"apply_filter()"方法就轻松实现了多态 
# ruby没有接口，只要方法名匹配，就能轻松的实现了多态特性 
require 'test/unit'
class FilterTest < Test::Unit::TestCase
  def test_filters
    fltrs = [simplefilter.new('oo'), regexfilter.new(/go+gle/)]
    fltrs.each do |fltr|
      assert(fltr.apply_filter('I love to Google'))
    end
  end
end
```


在Ruby中，class从来(几乎从来)不是type，相反，对象类型是根据对象能作什么决定的，即对象的behavior(method)。