2007-12-17
Ruby中的Mixin
关键字: ruby mixin
在Ruby中,我们可以把一个模块混入(Mixin)到对象中,从而达到类似多重继承的效果。
下面举几个例子来仔细阐述一下这个问题:
首先定义一个Module:
module Foo
def bar
puts "foo";
end
end
然后我们把这个模块混入到对象中去:
class Demo
include Foo
end
如上编码后,模块中的实例方法就会被混入到对象中:
d=Demo.new
d.bar
会输出foo字样。
下面我们重新定义一下Demo类:
class Demo
extend Foo
end
这个时候如果你得到的就是静态调用:
Demo.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
include Foo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
会输出demo字样。
其中的味道,自己慢慢体会吧。
下面举几个例子来仔细阐述一下这个问题:
首先定义一个Module:
module Foo
def bar
puts "foo";
end
end
然后我们把这个模块混入到对象中去:
class Demo
include Foo
end
如上编码后,模块中的实例方法就会被混入到对象中:
d=Demo.new
d.bar
会输出foo字样。
下面我们重新定义一下Demo类:
class Demo
extend Foo
end
这个时候如果你得到的就是静态调用:
Demo.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
include Foo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
会输出demo字样。
其中的味道,自己慢慢体会吧。
- 20:30
- 浏览 (450)
- 评论 (0)
- 发布在 Thinking In Ruby 圈子
- 相关推荐
发表评论
- 浏览: 610 次
- 性别:

- 来自: 北京

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
在Windows操作系统上搭建 ...
To weiqingfei:在 Windows 平台下安装 Ruby 有几个选择 ...
-- by 老王 -
在Windows操作系统上搭建 ...
好像安装ruby后不会自动安装gem吧,你怎么安装rails。
-- by weiqingfei -
在Windows操作系统上搭建 ...
To dualface: 廖兄也搞搞Ruby吧。
-- by 老王 -
在Windows操作系统上搭建 ...
沙发.....
-- by dualface






评论排行榜