Sharing Functionality: Inheritance, Modules, and Mixins(Chapter 5 of Programming Ruby)

本文深入探讨了Ruby中Mixins的概念,解释了它们如何提供命名空间防止名称冲突,并通过实例展示了如何将模块混合到类中,使得模块的所有实例方法成为类的一部分。文章还详细介绍了方法查找的顺序,即首先在对象的直接类中查找,然后在包含的模块中查找,最后在超类及其模块中查找。
  Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits:
  • Modules provide a namespace and prevent name clashes.
  • Modules support the mixin facility.

  You can include a module within a class definition. When this happens, all the module’s instance methods are suddenly available as methods in the class as well. They get mixed in. In fact, mixed-in modules effectively behave as superclasses. 

 

ExpandedBlockStart.gifmixin
 1 module Debug
 2   def who_am_i?
 3     "#{self.class.name} (\##{self.object_id}): #{self.to_s}"
 4   end
 5 end
 6 
 7 class Phonograph
 8   include Debug
 9   # ...
10 end
11 
12 class EightTrack
13   include Debug
14   # ...
15 end
16 
17 ph = Phonograph.new("West End Blues")
18 et = EightTrack.new("Surrealistic Pillow")
19 ph.who_am_i? # => "Phonograph (#330450): West End Blues"
20 et.who_am_i? # => "EightTrack (#330420): Surrealistic Pillow"

 

 

 

  One of the other questions folks ask about mixins is, how is method lookup handled? In particular, what happens if methods with the same name are defined in a class, in that class’s parent class, and in a mixin included into the class?

  The answer is that Ruby looks first in the immediate class of an object, then in the mixins included into that class, and then in superclasses and their mixins. If a class has multiple modules mixed in, the last one included is searched first. 

转载于:https://www.cnblogs.com/zhtf2014/archive/2010/06/28/1766641.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值