我们什么时候使用ruby模块和使用类组合?

cod*_*ver 9 ruby inheritance multiple-inheritance composition mixins

之前已经提出过与此类似的问题,但我特别要求使用组合作为使用模块mixins的替代方法.

class Helper
  def do_somthing
  end
end
Run Code Online (Sandbox Code Playgroud)

如果我需要"使用"一个类而不是继承它,我只需要编写并使用它.

class MyStuff
  def initialize
    helper = Helper.new
    helper.do_something
  end
end
Run Code Online (Sandbox Code Playgroud)

为什么我要为此创建一个模块:

 module Helper
   def do_something
   end
 end

class MyStuff
  include Helper
end
Run Code Online (Sandbox Code Playgroud)

我看到的唯一区别是,Helper如果我使用模块,周围不会有很多物体.但是我没有看到任何东西,周围有更多物体,而不是更大的物体.

而且,我不知道将来是否需要将其子类化.那么我该如何判断我的库的用户是想要使用模块mixin,还是想要使用合成?

Mic*_*ker 15

HelperMyStuff类之间的关系是所有权之一时,使用组合.这被称为"has-a"关系.例如,假设您有Person班级和Car班级.你会使用作文,因为一个人有车:

class Person
  def initialize
    @car = Car.new
  end
end

class Car
  def accelerate
    # implementation
  end
end
Run Code Online (Sandbox Code Playgroud)

Helper "表现得像"时 MyStuff,使用模块mixin.Helper在这种情况下,需要对角色MyStuff.这与"is-a"关系略有不同,这意味着您应该使用传统继承.例如,假设我们有一个Person类和一个Sleeper模块.一个人承担了卧铺的角色的时候,但是这样做的其他对象-实例Dog,Frog或者甚至Computer.其他每一类都代表着可以入睡的东西.

module Sleeper
  def go_to_sleep
    # implementation
  end
end

class Person
  include Sleeper
end

class Computer
  include Sleeper
end
Run Code Online (Sandbox Code Playgroud)

Sandi Metz的Ruby实用面向对象设计是这些主题的优秀资源.