在 ruby 中經常會使用到 Class,也常常看到 Module
那到底什麼時候要用哪個?
先看看兩者的差異
Module
- 無法 instantiated(也就是沒有 new method)
- 可以被 include & extend
Class
- 可以 instantiated
- 無法被 include
簡單的來說,module 有點像是沒有 new 的 Class
並且可以用 include & extend mixin 到 Class 裡面,變成 Class 的 class method or instance method
Ruby 中的 Include Extend Require Load
基本上兩種方式都有辦法達成同樣的效果,但差別就在於維護上
維護
用 Class 的話,勢必一定要先 new 出來,並且預設會執行 initialize 這個method
就可以預先設定好一些參數,看起來就會比較簡潔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
另外是當 Class include 很多 module 時,都會變成 Class 的 class method or instance method,這時就很難去分辨是從哪個 module 來的 method。
因此使用上,看習慣,可維護性等等,去判斷要用 module or class
再細分要放在 cocern or service object or lib
官方文件:
參考文件: