---
title: "mixin"
author: "yangbinfc"
date: "2011-01-24T10:15:00Z"
tags: []
slug: "mixin"
draft: false
lastmod: "2012-11-04T17:48:04Z"
id: 1715384
url: "https://yangbinfc.iteye.com/blog/1715384"
---

在 Matz 的一篇 PPT “Object-Oriented scripting in Ruby”中， Matz 提到 Ruby 提供一种语言机制 Mix-in ，在其 PPT 中如是描述的“ No Multiple Inheritance ， but Mix-in ”、“ Mix-in is as strong as multiple inheritance ， but simple ”。

**“module” in Ruby**

在 C++ 、 Java 、 C# 中都有 namespace 的概念，是用来隔离代码，防止代码冲突的。在 Ruby 中是采用“ module ”这个关键字来完成 namespace 功能的。

//considering the following code:

//MicrosoftCompiler.rb

module Microsoft

def Microsoft.compile

print "This is microsoft's compiler", "/n"

end

end

//SunCompiler.rb

module Sun

def Sun.compile

print "This is Sun's compiler", "/n"

end

end

//TestCompiler.rb

require "D://Ruby//MicrosoftCompiler.rb"

require "D://Ruby//SunCompiler.rb"

Microsoft.compile

Sun.compile

//output:

&gt;ruby TestComplier.rb

This is microsoft's compiler

This is Sun's compiler

&gt;Exit code: 0

module 除了体现 namespace 的概念外，从上面代码中我们还可以看到在两个 module 中定义的 method 和调用这个 method 时都在其前面加上其所在 module 的名字了。这样定义的函数叫 **module method** 。但是不是所有要使用 module 中函数都要显式的加上 module 名字呢？答案：不是。请往下看。

**Mix-in** **：** **Another wonderful use of “module”**

由 module method 的定义和调用方式让我们联想到 class method （注意不是 class instance method ），也让我们从 module 联想到 class 了。但是 A module 是不能像 class 那样拥有实例的， module 毕竟还不是 class ，但是我们可以在 class 的定义中“ include ”一个 module ，这样会发生什么呢？

//considering the following code:

module Mammal # 哺乳动物

def suckle # 哺乳

print "I can suckle my baby" ,"/n"

end

end

module Flyable # 可飞行的

def fly # 飞行

print "I can fly", "/n"

end

end

class Chiropter # 蝙蝠

include Mammal # 蝙蝠是哺乳动物

include Flying # 蝙蝠可以飞行

end

aChiropter = Chiropter.new

aChiropter.suckle

aChiropter.fly

//output ：

&gt;ruby TestMixin.rb

I can suckle my baby

I can fly

&gt;Exit code: 0

如上面代码得出的结果我们可以看出，一旦一个 class 中 include 了一个 module, 那么所有 module 中的 methods 就好像成为 class’s instance methods 一样，这就是 mix-in ，看起来被 mix-in 的 modules 的行为更像是这个 class 的 super class ，通过这种方法我们可以间接实现多重继承。但是注意看看被 mixin 的 module 中的函数是如何定义的？和前面代表 namespace 概念的 module 中的 method 定义不同的是在于定义时 method name 前不见了 module name ，这样定义出来的 method 叫 **module instance method** , 虽然 module 不能实例化，但是一旦被 mixin 到某个 class 中，这些 module instance method 的使用就等价于 class instance method 了。

**总结：**

1\. Module 的两种用法

Ø 体现 namespace 概念；

Ø 被 mixin 到 class 中间接的实现类的多重继承。

2\. Module 中的两种 method 定义和用法

module module\_name

def **module\_name.** module\_method\_name

\# module method , for representing namespace concept

end

def module\_instance\_method\_name

\# module instance method

\# Once the module has been mixed in,

#the method will be equal to a class instance method

end

end