之前已经提出过类似这样的问题,但是我特别提出了使用组合作为使用模块mixin的替代方法。什么时候使用ruby模块vs使用类组合?
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
对象躺在身边,如果我使用的模块。但是我没有看到有更多物体躺在较小的物体上。
此外,我不知道我是否需要在未来继承它。那么,如何决定我的库的用户是否想要使用模块mixin,或者想要使用组合?
'require'不是你在这里需要的。你需要'include'。 – Linuxios
thnx。修正 – codeObserver
当然。乐意效劳。 – Linuxios