一般,避免混入訪問成員變量:這是一種非常緊密的耦合形式,可能會使未來的重構變得不必要的困難。
一個有用的策略是讓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