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的实现原理,看过的知识点,自己在写一遍,我心里才会感觉踏实,所以就摘录了这篇文章。