何时使用嵌套类和模块中嵌套的类? [英] When to use nested classes and classes nested in modules?
问题描述
我对何时使用子类和模块非常熟悉,但是最近我看到了这样的嵌套类:
I'm pretty familiar with when to use subclasses and modules, but more recently I've been seeing nested classes like this:
class Foo
class Bar
# do some useful things
end
end
以及嵌套在模块中的类,例如:
As well as classes nested in modules like so:
module Baz
class Quux
# more code
end
end
无论是文档还是文章都很稀少,或者我对这个主题的知识不够了解,无法找到合适的搜索词,但是我似乎找不到太多关于该主题的信息.
Either documentation and articles are sparse or I'm not educated on the subject enough to grope for the right search terms, but I can't seem to locate much information on the topic.
有人可以提供示例或链接到有关为什么/何时使用这些技术的帖子吗?
Could somebody provide examples or links to posts on why/when those techniques would be used?
推荐答案
其他OOP语言具有内部类必须绑定到上层类才能实例化.例如,在Java中,
Other OOP languages have inner classes which cannot be instantiated without being bound to an upper level class. For instance, in Java,
class Car {
class Wheel { }
}
仅Car
类中的方法可以创建Wheel
s.
only methods in the Car
class can create Wheel
s.
Ruby没有这种行为.
Ruby doesn’t have that behaviour.
在Ruby中,
class Car
class Wheel
end
end
与
class Car
end
class Wheel
end
仅以类Wheel
与Car::Wheel
的名称进行比较.名称上的这种差异可以向程序员明确表明Car::Wheel
类只能表示车轮,而不是普通车轮.在Ruby中嵌套类定义是一个优先选择的问题,但在某种意义上说,这样做的目的是更强有力地在两个类之间强制执行契约,从而传达有关它们及其用途的更多信息.
only in the name of the class Wheel
vs. Car::Wheel
. This difference in name can make explicit to programmers that the Car::Wheel
class can only represent a car wheel, as opposed to a general wheel. Nesting class definitions in Ruby is a matter of preference, but it serves a purpose in the sense that it more strongly enforces a contract between the two classes and in doing so conveys more information about them and their uses.
但是对于Ruby解释器来说,只是名称有所不同.
But to the Ruby interpreter, it’s only a difference in name.
关于您的第二个观察,嵌套在模块内部的类通常用于命名这些类的名称空间.例如:
As for your second observation, classes nested inside of modules are generally used to namespace the classes. For instance:
module ActiveRecord
class Base
end
end
与
module ActionMailer
class Base
end
end
虽然这不是嵌套在模块内部的类的唯一用途,但通常是最常见的.
Although this is not the only use of classes nested inside of modules, it is generally the most common.
这篇关于何时使用嵌套类和模块中嵌套的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!