一般,避免混入访问成员变量:这是一种非常紧密的耦合形式,可能会使未来的重构变得不必要的困难。
一个有用的策略是让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"
的混入访问“文本”访问,这是由包括类定义:
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
使用混入普通和常见的数据名称时,包括类使用相同的名称可能会导致冲突。在这种情况下,有混入查找数据与不太常见的名字:
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"
通过这种方式,存取作为排序混音输入数据和包含类别数据之间的“阻抗匹配器”或“翻译器”。
谢谢韦恩,你真的清除了这一点。 – dangerousdave 2010-02-19 20:54:03