0
我有以下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
IncompleteContact
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
,但希望听到更多有经验的人的意见。读这本书(以及一些现场体验)让我明白了多少去耦很重要
我会去:do不用担心ruby中的依赖注入。 ':: ContractorUi :: ContactSource'只是一个常量(在ruby中常量不是很常量),它持有对类的引用 - 你可以在任何你想要的地方保留这个常量。当类是静态时,依赖注入是重要的。 – BroiSatse 2014-10-27 12:08:11
感谢您的建议,请注意,在任何情况下我都不担心,Ruby已经允许我绕过任何大问题,并且在我的测试中,我只为ContactSource类存根generate_xxx。不过,我想从教学的角度来看,如果将依赖关系保留在那里是一个好主意。 – 2014-10-27 12:27:47