除了构造函数替换之外,还可以将信息存储在实例变量(“属性”)中。从你的例子来看:
class A
end
class B
attr_accessor :client_impl
def connect
@connection = @client_impl.new.connect
end
end
b = B.new
b.client_impl = Twitterbot
b.connect
您还可以允许依赖项作为方法的一个选项提供:
class A
end
class B
def connect(impl = nil)
impl ||= Twitterbot
@connection = impl.new.connect
end
end
b = B.new
b.connect
b = B.new
b.connect(Facebookbot)
您还可以混合搭配技术:
class A
end
class B
attr_accessor :impl
def initialize(impl = nil)
@impl = impl || Twitterbot
end
def connect(impl = @impl)
@connection = impl.new.connect
end
end
b = B.new
b.connect # Will use Twitterbot
b = B.new(Facebookbot)
b.connect # Will use Facebookbot
b = B.new
b.impl = Facebookbot
b.connect # Will use Facebookbot
b = B.new
b.connect(Facebookbot) # Will use Facebookbot
基本上,当人们谈论Ruby和DI时,他们的意思是语言本身足够灵活,可以在不需要特殊框架的情况下实现任意数量的DI样式。