一般来说,避免让 mixins 访问成员变量:这是一种非常紧密的耦合形式,可能会使未来的重构变得不必要地困难。
一种有用的策略是让 Mixin 始终通过访问器访问变量。所以,而不是:
#!/usr/bin/ruby1.8
module Mixin
def do_something
p @text
end
end
class Foo
include Mixin
def initialize
@text = 'foo'
end
end
Foo.new.do_something # => "foo"
mixin 访问由包含类定义的“文本”访问器:
module Mixin
def do_something
p text
end
end
class Foo
attr_accessor :text
include Mixin
def initialize
@text = 'foo'
end
end
Foo.new.do_something # => "foo"
如果你需要在这个类中包含 Mixin 怎么办?
class Foo
def initialize
@text = "Text that has nothing to do with the mixin"
end
end
当包含类使用相同的名称时,在 mixin 中使用通用和通用数据名称可能会导致冲突。在这种情况下,让 mixin 查找名称不太常见的数据:
module Mixin
def do_something
p mixin_text
end
end
并让包含类定义适当的访问器:
class Foo
include Mixin
def initialize
@text = 'text that has nothing to do with the mixin'
@something = 'text for the mixin'
end
def mixin_text
@something
end
end
Foo.new.do_something # => "text for the mixin"
通过这种方式,访问器充当混合数据和包含类数据之间的“阻抗匹配器”或“转换器”。