重新认识ruby的多态和duck type
多态在java中是如何定义的?我这样理解:
多态需要借助接口来实现,就是所有实现了该特定的接口的类用起来都象他。
什么是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
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的多态和duck type"由远航站长收集整理而来,仅供大家学习与参考使用。更多网站制作教程尽在远航站长站。
顶一下
(0)
0%
踩一下
(0)
0%