
-- Elements: plain tables, kind names the type
local car = {kind = "car", items = {
{kind = "engine"},
{kind = "wheel", number = 1},
{kind = "wheel", number = 2},
}}
-- ConcreteVisitor: a function for each kind
local test_car_visitor = {
engine = function()
print("test engine")
end,
wheel = function(wheel)
print("test wheel #" .. wheel.number)
end,
car = function()
print("test car")
end,
}
-- ConcreteVisitor: new work for the same
-- elements, the elements stay untouched
local repair_car_visitor = {
engine = function()
print("repair engine")
end,
wheel = function(wheel)
print("repair wheel #" .. wheel.number)
end,
car = function()
print("repair car")
end,
}
-- accept: the parts first, then the element;
-- its kind picks the function of the visitor
local function accept(element, visitor)
for _, item in ipairs(element.items or {}) do
accept(item, visitor)
end
visitor[element.kind](element)
end
-- Client
accept(car, test_car_visitor)
accept(car, repair_car_visitor)
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.Read more问题。一份文档由段落、图片和表格组成。程序必须能导出文档、统计字数并检查拼写。如果把每个操作都作为方法加到每一种组成部分上,每增加一个操作,这些部分的类就膨胀一次。而且一个操作的代码还会分散在许多类中。 思路。每个操作都变成一个单独的对象,称为访问者。访问者为每一种元素各准备一个方法。每个元素有一个方法,它接收一个访问者,并调用访问者中对应自己种类的方法。这样,每一对元素和操作都会运行正确的代码,无需检查类型。要增加一个新操作,只需编写一个新的访问者;元素类保持不变。 如何阅读示例。元素分为几种。每个具体访问者是一个操作,为每一种元素各有一个单独的方法。客户端代码把访问者交给元素,每个元素再把它送到对应自己种类的方法。在大多数示例中,一个元素包含其他元素,并把访问者交给自己的每个组成部分。随后两个访问者依次经过同样的这些部分,各自执行自己的操作。在某些语言中,元素是带有类型标签的普通数据,访问者是一个函数,为每一种元素各有一个版本。 何时使用。当元素类的集合保持稳定、而针对它们的新操作经常出现时,使用访问者模式。经常增加新的元素种类时不要使用它:每增加一种元素,每个访问者都需要一个新方法。 常见错误。在一个通用的访问者方法内部用条件判断检查元素的类型。这样,新的元素种类会在毫无警告的情况下被遗漏。应为每一种元素提供它自己的方法。 |