HeadFirst Ruby 第九章总结 mixins & modules

前言

如果想要复用 method, 可用的方法是针对 Class 的 inheritance,但是, inheritance has its limitations,它的缺点有:

  1. 只能 inhert 一个 Class 
  2. Class 的名称有一定的意义,怪异的 inheritance 会导致 class 中的方法多余,或者导致 collegues 的 misundertanding

在 Ruby 中, 可以使用 module 来解决这个问题.

关于 Modules & Mix-ins

Modules :

内容格式:与 Class 的格式相似

module MyModule
def first_method
puts "first method called."
end
def second_method
puts "second method called"
end
end

注意:
与 Class 不同的地方:不能进行 new 创建 instance

Modules 功能

它是一个 collection of methods,

When you mix a module into a class, it's like adding all of the module's methods to the class as instance method.

Mix-in 相关

引用格式: include

class MyClass
include MyModule
end

Mix-in 定义:

Modules that are designed to be mixed into classes 被称作 Mix-ins.

Mix-in 地位 & ancestor 方法

ancestor 方法:通过调用一个对象的 ancestor 方法,可以查看调用其方法时查找所需方法的顺序.
Mix-in 地位: Mix-in 的位置位于当前 Class 和 SuperClass 之间.

特别注意的一点: 在 Module 中 avoid using "initialize"

想達到的目的: 使用 Module 來 set a default value for a variable.
问题原因:
由于 MIx-in 地位的缘故,它的运行机制和当前 Class 的一个 SuperClass 很 Similar, 因此如果在当前 Class 使用 initialize 方法就会 override Module 中的 initialize.
解决办法:

  1. 使用条件语句:
    def comments 
    if @comments
    @comments
    else
    @comments = []
    end
    end
  2. [简化] 使用“ || ”运算符, 例如p nil||[]





原文地址:https://www.cnblogs.com/FBsharl/p/10560234.html