Ruby是单继承的语言,和iOS中的swift类似,swift也是单继承,在swift中,我们可以使用 protocol 和 extension组合的方式,来实现多继承的效果。在Ruby中,多继承可以使用module和include组合的方式实现多继承的效果。
Mix-in
class Person // 1
end
module PlayPianoMixin // 2
def playPiano
puts "正在弹钢琴..."
end
end
class XiaoMing < Person
include PlayPianoMixin //3
end
p1 = XiaoMing.new()
p1.playPiano() // 4
输出结果:
正在弹钢琴...
- 1,定义一个
Person类。 - 2,定义一个
PlayPianoMixin的module。 - 3,在具体类里面
inclue特定的module。
通过这种方式,我们将PlayPian抽象成了一个modlue,当描述对应class时需要的时候,就使用Mix-in模式将其inclue就可以获得对应的能力。
Mix-in期望是一个行为的集合,并且这个行为可以添加到任意的class中,从某种程度上来说,继承描述的是 “它是什么”,而 Mix-in描述的是“它能做什么",从这一点出发,Mix-in 的设计是单一职责的,并且Mix-in实际上对宿主类一无所知
Mix-in in Cocoapods
在 CocoaPods的 config.rb,其中有很多关于Pods的配置字段、CocoaPods的一些关键目录,并且还持有一些单例的 Manager。
// config.rb
# Provides support for accessing the configuration instance in other
# scopes.
#
module Mixin
def config
Config.instance
end
end
通过 Mix-in模式,定义了一个单例。在别的文件中,通过 include来获取,从而方便的获取一些配置信息
// installer.rb
class Installer
include Config::Mixin
....
def integrate_user_project
...
installation_root = config.installation_root
end
end
inclue之后,就可以直接使用config对象了。
本文摘录自 一瓜技术的 CocoaPods 中的 Ruby 特性之 Mix-in,作者最近正在学习 Ruby和学习Cocoapods的实现原理,看过的知识点,自己在写一遍,我心里才会感觉踏实,所以就摘录了这篇文章。