嘿那里,我已经阅读了几篇关于何时/如何使用访问者模式的帖子,以及一些关于它的文章/章节,如果你正在遍历一个AST并且它结构高,你想要将逻辑封装到一个单独的“访问者”对象等等。但是使用Ruby,它似乎有点过分,因为你可以使用块来做几乎相同的事情。
我想使用Nokogiri的pretty_print xml。作者建议我使用访问者模式,这需要我创建一个FormatVisitor或类似的东西,所以我可以说“node.accept(FormatVisitor.new)”。
问题是,如果我想开始自定义FormatVisitor中的所有内容(例如,它允许您指定节点的选项卡方式,属性如何排序,属性如何间隔等等)。
我有几个选择:
不必构造FormatVisitor,设置值,并将其传递给node.accept方法,为什么不这样做:
node.pretty_print do |format|
format.tabs = 2
format.sort_attributes_by {...}
end
这与我觉得访客模式看起来形成鲜明对比:
node.pretty_print do |format|
format.tabs = 2
format.sort_attributes_by {...}
end
也许我的访客模式都错了,但是从我在红宝石中读到的那些,看起来有点矫枉过正。你怎么看?无论哪种方式对我都没问题,只是想知道你们对此感觉如何。
非常感谢, 兰斯
答案 0 :(得分:13)
本质上,Ruby块是访问者模式,没有额外的样板。对于琐碎的情况,一个块就足够了。
例如,如果要对Array对象执行简单操作,只需使用块调用#each
方法,而不是实现单独的Visitor类。
但是,在某些情况下实施具体的访客模式有一些优势:
您的实现似乎有点复杂,并且Nokogiri期望一个访问者实例具有推动#visit
方法,因此访问者模式实际上非常适合您的特定用例。以下是访问者模式的基于类的实现:
FormatVisitor实现#visit
方法,并根据节点类型和其他条件使用Formatter
子类格式化每个节点。
# FormatVisitor implments the #visit method and uses formatter to format
# each node recursively.
class FormatVistor
attr_reader :io
# Set some initial conditions here.
# Notice that you can specify a class to format attributes here.
def initialize(io, tab: " ", depth: 0, attributes_formatter_class: AttributesFormatter)
@io = io
@tab = tab
@depth = depth
@attributes_formatter_class = attributes_formatter_class
end
# Visitor interface. This is called by Nokogiri node when Node#accept
# is invoked.
def visit(node)
NodeFormatter.format(node, @attributes_formatter_class, self)
end
# helper method to return a string with tabs calculated according to depth
def tabs
@tab * @depth
end
# creates and returns another visitor when going deeper in the AST
def descend
self.class.new(@io, {
tab: @tab,
depth: @depth + 1,
attributes_formatter_class: @attributes_formatter_class
})
end
end
这里是上面使用的AttributesFormatter
的实现。
# This is a very simple attribute formatter that writes all attributes
# in one line in alphabetical order. It's easy to create another formatter
# with the same #initialize and #format interface, and you can then
# change the logic however you want.
class AttributesFormatter
attr_reader :attributes, :io
def initialize(attributes, io)
@attributes, @io = attributes, io
end
def format
return if attributes.empty?
sorted_attribute_keys.each do |key|
io << ' ' << key << '="' << attributes[key] << '"'
end
end
private
def sorted_attribute_keys
attributes.keys.sort
end
end
NodeFormatter
使用Factory模式为特定节点实例化正确的格式化程序。在这种情况下,我将文本节点,叶元素节点,元素节点与文本和常规元素节点区分开来。每种类型都有不同的格式要求。另请注意,这不完整,例如注释节点不被考虑在内。
class NodeFormatter
# convience method to create a formatter using #formatter_for
# factory method, and calls #format to do the formatting.
def self.format(node, attributes_formatter_class, visitor)
formatter_for(node, attributes_formatter_class, visitor).format
end
# This is the factory that creates different formatters
# and use it to format the node
def self.formatter_for(node, attributes_formatter_class, visitor)
formatter_class_for(node).new(node, attributes_formatter_class, visitor)
end
def self.formatter_class_for(node)
case
when text?(node)
Text
when leaf_element?(node)
LeafElement
when element_with_text?(node)
ElementWithText
else
Element
end
end
# Is the node a text node? In Nokogiri a text node contains plain text
def self.text?(node)
node.class == Nokogiri::XML::Text
end
# Is this node an Element node? In Nokogiri an element node is a node
# with a tag, e.g. <img src="foo.png" /> It can also contain a number
# of child nodes
def self.element?(node)
node.class == Nokogiri::XML::Element
end
# Is this node a leaf element node? e.g. <img src="foo.png" />
# Leaf element nodes should be formatted in one line.
def self.leaf_element?(node)
element?(node) && node.children.size == 0
end
# Is this node an element node with a single child as a text node.
# e.g. <p>foobar</p>. We will format this in one line.
def self.element_with_text?(node)
element?(node) && node.children.size == 1 && text?(node.children.first)
end
attr_reader :node, :attributes_formatter_class, :visitor
def initialize(node, attributes_formatter_class, visitor)
@node = node
@visitor = visitor
@attributes_formatter_class = attributes_formatter_class
end
protected
def attribute_formatter
@attribute_formatter ||= @attributes_formatter_class.new(node.attributes, io)
end
def tabs
visitor.tabs
end
def io
visitor.io
end
def leaf?
node.children.empty?
end
def write_tabs
io << tabs
end
def write_children
v = visitor.descend
node.children.each { |child| child.accept(v) }
end
def write_attributes
attribute_formatter.format
end
def write_open_tag
io << '<' << node.name
write_attributes
if leaf?
io << '/>'
else
io << '>'
end
end
def write_close_tag
return if leaf?
io << '</' << node.name << '>'
end
def write_eol
io << "\n"
end
class Element < self
def format
write_tabs
write_open_tag
write_eol
write_children
write_tabs
write_close_tag
write_eol
end
end
class LeafElement < self
def format
write_tabs
write_open_tag
write_eol
end
end
class ElementWithText < self
def format
write_tabs
write_open_tag
io << text
write_close_tag
write_eol
end
private
def text
node.children.first.text
end
end
class Text < self
def format
write_tabs
io << node.text
write_eol
end
end
end
要使用此课程:
xml = "<root><aliens><alien><name foo=\"bar\">Alf<asdf/></name></alien></aliens></root>"
doc = Nokogiri::XML(xml)
# the FormatVisitor accepts an IO object and writes to it
# as it visits each node, in this case, I pick STDOUT.
# You can also use File IO, Network IO, StringIO, etc.
# As long as it support the #puts method, it will work.
# I'm using the defaults here. ( two spaces, with starting depth at 0 )
visitor = FormatVisitor.new(STDOUT)
# this will allow doc ( the root node ) to call visitor.visit with
# itself. This triggers the visiting of each children recursively
# and contents written to the IO object. ( In this case, it will
# print to STDOUT.
doc.accept(visitor)
# Prints:
# <root>
# <aliens>
# <alien>
# <name foo="bar">
# Alf
# <asdf/>
# </name>
# </alien>
# </aliens>
# </root>
使用上面的代码,您可以通过构造NodeFromatter
的额外子类来更改节点格式化行为,并将它们插入到工厂方法中。您可以使用AttributesFromatter
的各种实现来控制属性的格式。只要您遵守其界面,就可以将其插入attributes_formatter_class
参数,而无需修改其他任何内容。
使用的设计模式列表:
NodeFormatter
上的类方法,则可以将它们提取到NodeFormatterFactory
中以使其更合适。这演示了如何将几种模式组合在一起以实现所需的灵活性。虽然,如果你需要那些灵活性是你必须决定的。
答案 1 :(得分:7)
我会选择简单而有效的方法。我不知道细节,但你写的与访客模式相比,看起来更简单。如果它也适合你,我会用它。就个人而言,我厌倦了所有这些技术,要求你创建一个巨大的“网络”相互关联的类,只是为了解决一个小问题。
有些人会说,是的,但是如果你使用模式做,那么你可以涵盖许多未来的需求,等等等等。我说,现在做什么有效,如果需要,你可以在将来进行重构。在我的项目中,几乎从未出现这种需求,但这是一个不同的故事。