首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Ruby 模組與 Mixin 機制:命名空間、多重繼承替代方案

     編輯:更多程式設計知識

模組是 Ruby 實現命名空間隔離與程式碼複用(Mixin)的核心機制。本文說明模組定義、require/include、常數存取、以及 Mixin 如何替代多重繼承。

模組基本特性

  • 提供命名空間,避免名稱衝突
  • 實現 Mixin,替代多重繼承
  • 可包含方法、類別、常數

模組定義與使用

module Trig
  PI = 3.141592654
  def Trig.sin(x); ... end
  def Trig.cos(x); ... end
end

module Moral
  VERY_BAD = 0
  def Moral.sin(badness); ... end
end

呼叫模組方法:Trig.sin(Trig::PI/4)
存取常數:Trig::PI

require 載入模組

require 'trig'
require 'moral'
y = Trig.sin(Trig::PI/4)
模組避免同名方法衝突,需以模組名限定呼叫。

include 將模組混入類別

# support.rb
module Week
  FIRST_DAY = "Sunday"
  def Week.weeks_in_month; puts "一月四週"; end
  def Week.weeks_in_year; puts "一年52週"; end
end

# 主程式
require "support"
class Decade
  include Week
  def no_of_months
    puts Week::FIRST_DAY
    puts 10 * 12
  end
end

d1 = Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d1.no_of_months

Mixin:替代多重繼承

Ruby 不支援多重繼承,但可 include 多個模組:

module A; def a1; end; def a2; end; end
module B; def b1; end; def b2; end; end

class Sample
  include A
  include B
  def s1; end
end

samp = Sample.new
samp.a1; samp.a2; samp.b1; samp.b2; samp.s1  # 全部可呼叫

Sample 同時擁有 A、B 的方法,實現「多重繼承」效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved