【发布时间】:2014-10-30 04:41:11
【问题描述】:
我有以下 3 个课程:
基础
module TitleSource
class Base
include Comparable
attr_accessor :company
attr_accessor :priority
attr_accessor :target_title
def initialize(args={})
self.company = args[:company]
self.priority = args[:priority]
self.target_title = args[:target_title]
end
def create_contact_source
raise NotImplementedError
end
def <=>(other)
fetch_value <=> other.fetch_value
end
protected def fetch_value
value
end
private def value
raise NotImplementedError
end
end
end
UnmatchedTitle
module TitleSource
class UnmatchedTitle < Base
def create_contact_source
::ContractorUi::ContactSource.generate_from_unmatched_title(self)
end
private def value
100
end
end
end
不完整的联系
module TitleSource
class IncompleteContact < Base
attr_accessor :target_title_name
attr_accessor :contact
def initialize(args={})
super
self.target_title_name = args[:target_title_name]
self.contact = args[:contact]
end
def create_contact_source
::ContractorUi::ContactSource.generate_from_incomplete_contact(self)
end
private def value
10
end
end
end
我目前正在阅读 POODR 并提出了这个设计,到目前为止对我很有帮助。
但是,出于教学原因,我想知道如何消除对 ::ContractorUi::ContactSource 的依赖,如果值得以及是否应该这样做。
我不喜欢将它与构造函数一起传递的想法,因为TitleSource 模块的全部目的是实际生成ContactSource,但想听听更有经验的人的意见。阅读这本书(以及一些现场经验)让我明白了解耦有多么重要
【问题讨论】:
-
我会选择:不要担心 ruby 中的依赖注入。
::ContractorUi::ContactSource只是一个常量(并且 ruby 中的常量不是那么常量),它包含对类的引用——你可以在任何你想要的地方存根这个常量。当类是静态的时,依赖注入很重要。 -
感谢您的建议,请注意,无论如何我都不担心,Ruby 已经允许我解决任何大问题,并且在我的测试中,我只是为 ContactSource 类存根 generate_xxx。但是,我想从教学的角度了解将依赖项保留在那里是否是个好主意。
标签: ruby dependency-injection dependencies decoupling