Lan*_*ard 8 ruby design-patterns visitor
嘿那里,我已经阅读了关于何时/如何使用访问者模式的一些帖子,以及它上面的一些文章/章节,如果你正在遍历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
Run Code Online (Sandbox Code Playgroud)
这与我觉得访客模式看起来形成鲜明对比:
visitor = Class.new(FormatVisitor) do
attr_accessor :format
def pretty_print(node)
# do something with the text
@format.tabs = 2 # two tabs per nest level
@format.sort_attributes_by {...}
end
end.new
doc.children.each do |child|
child.accept(visitor)
end
Run Code Online (Sandbox Code Playgroud)
也许我的访客模式都是错误的,但是从我在红宝石中读到的那些,看起来有点矫枉过正.你怎么看?无论哪种方式都适合我,只是想知道你们对它的看法.
非常感谢Lance
Aar*_*ian 13
实质上,Ruby块是没有额外样板的访问者模式.对于琐碎的情况,块就足够了.
例如,如果要对Array对象执行简单操作,则只需#each使用块调用该方法,而不是实现单独的Visitor类.
但是,在某些情况下实施具体访客模式有一些优势:
你的实现似乎有点复杂,Nokogiri希望一个Visitor实例是impelment #visit方法,所以Visitor模式实际上非常适合你的特定用例.以下是访问者模式的基于类的实现:
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
Run Code Online (Sandbox Code Playgroud)
这里执行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
Run Code Online (Sandbox Code Playgroud)
NodeFormatters使用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
Run Code Online (Sandbox Code Playgroud)
要使用此类:
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>
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,您可以通过构造NodeFromatters的额外子类来更改节点格式化行为,并将它们插入到工厂方法中.您可以通过各种实现来控制属性的格式AttributesFromatter.只要您遵守其界面,就可以将其插入attributes_formatter_class参数而无需修改任何其他内容.
使用的设计模式列表:
NodeFormatter,可以将它们提取到NodeFormatterFactory更合适的位置.这演示了如何将几种模式组合在一起以实现所需的灵活性.虽然,如果你需要这些灵活性,你必须要做出决定.
我会选择简单而有效的方法.我不知道细节,但你写的与访客模式相比,看起来更简单.如果它也适合你,我会用它.就个人而言,我厌倦了所有这些技术,要求你创建一个巨大的相互关联的"网络",只是为了解决一个小问题.
有些人会说,是的,但是如果你使用模式来做,那么你可以涵盖许多未来的需求,等等等等.我说,现在做什么有效,如果需要,你可以在将来进行重构.在我的项目中,几乎从未出现过,但这是一个不同的故事.
| 归档时间: |
|
| 查看次数: |
2500 次 |
| 最近记录: |