Ruby模块可以被描述为单例类吗? [英] Can a Ruby module be described as a singleton class?
问题描述
Ruby模块本质上只是一个只初始化一次的类,
包含MyModule
一个ruby类是一个可以实例化的模块。像一个类,一个模块可以有方法,但你不能做一个模块的实例。这是他们之间的唯一区别。
在实践中,模块通常用于:
- 名字空格
- Mixins
- 保留功能
名称空间
以下是用作名称空间的模块的示例:
模块MyLib
class Foo
end
class Bar
end
end
这些类的全名是MyLib :: Foo和MyLib :: Bar。因为它们包含在命名空间(大概是唯一的)中,Foo和Bar的名称不能与您的程序或另一个库中定义的Foo或Bar发生冲突。
Mixin
这是一个用作混音的模块:
模块Mixin
def foo
putfoo
end
end
由于您无法创建Mixin模块的实例,您可以通过包含(混合)模块来访问foo:
class MyClass
include Mixin
end
MyClass.new.foo#=> foo
函数
模块可以容纳不在任何实例上操作的功能。为此,您可以在模块中定义类方法:
module SomeFunctions
def self.foo
putfoo
end
end
模块中定义的类方法就像在类中定义的类方法一样。调用它:
SomeFunctions.foo#=> foo
I'm trying to understand the purpose of a Ruby module from a design pattern perspective.
Is a Ruby module essentially just a class that is only initialized once?
include MyModule
A ruby class is a module you can make instances of. Like a class, a module can have methods, but you cannot make an instance of a module. That's the only difference between them.
In practice, modules are commonly used for:
- Name spaces
- Mixins
- To hold functions
Name Space
Here's an example of a module used as a name space:
module MyLib
class Foo
end
class Bar
end
end
The full name of these classes is MyLib::Foo and MyLib::Bar. Because they are contained in a namespace (which presumably is unique), the names Foo and Bar cannot conflict with a Foo or Bar defined in your program or in another library.
Mixin
Here's a module used as a mix-in:
module Mixin
def foo
puts "foo"
end
end
Since you can't make an instance of the Mixin module, you get access to foo by including (mixing in) the module:
class MyClass
include Mixin
end
MyClass.new.foo # => foo
Functions
Like a class, a module can hold functions that do not operate on any instance. To do that, you define class methods in the module:
module SomeFunctions
def self.foo
puts "foo"
end
end
A class method defined in a module is just like a class method defined in a class. To call it:
SomeFunctions.foo # => foo
这篇关于Ruby模块可以被描述为单例类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!