之前有类似的问题被问过,但我特别询问使用组合作为替代模块混入的方法。
class Helper
def do_somthing
end
end
如果我需要“使用”一个类但不继承它,我会简单地组合它并使用它。class MyStuff
def initialize
helper = Helper.new
helper.do_something
end
end
为什么我想要为此创建一个模块:
module Helper
def do_something
end
end
class MyStuff
include Helper
end
我看到的唯一区别是,如果我使用模块,就不会有许多Helper
对象。但我没有看到更多对象与较少更大的对象相比有什么不同。
此外,我不知道将来是否需要对其进行子类化。那么我如何决定我的库的用户想要使用模块混合,还是想要使用组合?
require
,你需要使用include
。 - Linuxios