一文读懂访问者模式

01 意图

访问者是一种行为设计模式,可让您将算法与它们操作的对象分开。

02 问题

想象一下,您的团队开发了一个应用程序,该应用程序将地理信息结构化为一个巨大的图表。图中的每个节点可能代表一个复杂的实体,例如城市,但也可能代表更细化的事物,例如工业、观光区等。如果在它们所代表的真实对象之间存在道路,则这些节点将与其他节点相连。在底层,每个节点类型都由它自己的类表示,而每个特定节点都是一个对象。

image.png

在某个时候,您需要执行将图形导出为 XML 格式的任务。起初,这项工作似乎很简单。您计划为每个节点类添加一个导出方法,然后利用递归遍历图的每个节点,执行导出方法。解决方案简单而优雅:由于多态性,您没有将调用导出方法的代码耦合到具体的节点类。

不幸的是,系统架构师不允许您更改现有的节点类。他说代码已经在生产中,他不想冒险破坏它,因为您的更改中存在潜在的错误。

图片

此外,他质疑在节点类中包含 XML 导出代码是否有意义。这些类的主要工作是处理地理数据。XML 导出行为在那里看起来很陌生。

拒绝还有另一个原因。很有可能在实施此功能后,营销部门的某个人会要求您提供导出为不同格式的功能,或者请求其他一些奇怪的东西。这将迫使您再次更改那些宝贵而脆弱的课程。

03 解决方案

访问者模式建议您将新行为放入一个名为visitor的单独类中,而不是尝试将其集成到现有类中。必须执行该行为的原始对象现在作为参数传递给访问者的方法之一,提供对对象中包含的所有必要数据的方法访问。

现在,如果该行为可以在不同类的对象上执行呢?例如,在我们的 XML 导出案例中,不同节点类的实际实现可能会略有不同。因此,访问者类可能定义的不是一个,而是一组方法,每个方法都可以接受不同类型的参数,如下所示:


class ExportVisitor implements Visitor is
    method doForCity(City c) { ... }
    method doForIndustry(Industry f) { ... }
    method doForSightSeeing(SightSeeing ss) { ... }
    // ...

但是我们如何准确地调用这些方法,尤其是在处理整个图形时?这些方法有不同的签名,所以我们不能使用多态性。要选择能够处理给定对象的适当访问者方法,我们需要检查它的类。这听起来不是一场噩梦吗?

foreach (Node node in graph)
    if (node instanceof City)
        exportVisitor.doForCity((City) node)
    if (node instanceof Industry)
        exportVisitor.doForIndustry((Industry) node)
    // ...
}

你可能会问,为什么我们不使用方法重载呢?那是你给所有方法命名的时候,即使它们支持不同的参数集。不幸的是,即使假设我们的编程语言完全支持它(就像 Java 和 C# 那样),它也无济于事。由于事先不知道节点对象的确切类,重载机制将无法确定要执行的正确方法。它将默认为采用基Node类对象的方法。

然而,访问者模式解决了这个问题。它使用一种称为Double Dispatch的技术,该技术有助于在对象上执行正确的方法,而无需繁琐的条件。与其让客户端选择要调用的方法的正确版本,不如将这个选择委托给我们作为参数传递给访问者的对象?由于对象知道它们自己的类,它们将能够为访问者选择一个合适的方法,而不那么尴尬。他们“接受”访问者并告诉它应该执行什么访问方法。


// Client code
foreach (Node node in graph)
    node.accept(exportVisitor)

// City
class City is
    method accept(Visitor v) is
        v.doForCity(this)
    // ...

// Industry
class Industry is
    method accept(Visitor v) is
        v.doForIndustry(this)
    // ...

我承认。毕竟我们不得不改变节点类。但至少更改是微不足道的,它让我们可以添加更多行为而无需再次更改代码。

现在,如果我们为所有访问者提取一个通用界面,所有现有节点都可以与您引入应用程序的任何访问者一起使用。如果您发现自己引入了与节点相关的新行为,您所要做的就是实现一个新的访问者类。

04 举个栗子

图片

想象一位经验丰富的保险代理人渴望获得新客户。他可以参观附近的每一栋建筑,试图向他遇到的每个人推销保险。根据占用建筑物的组织类型,他可以提供专门的保险单:

  • 如果是住宅楼,他卖医疗保险。

  • 如果是银行,他就卖盗窃保险。

  • 如果是咖啡店,他会卖火灾和洪水保险。

05 结构实现

图片

在此示例中,访问者模式将 XML 导出支持添加到几何形状的类层次结构中。

图片

// The element interface declares an `accept` method that takes
// the base visitor interface as an argument.
interface Shape is
    method move(x, y)
    method draw()
    method accept(v: Visitor)

// Each concrete element class must implement the `accept`
// method in such a way that it calls the visitor's method that
// corresponds to the element's class.
class Dot implements Shape is
    // ...

    // Note that we're calling `visitDot`, which matches the
    // current class name. This way we let the visitor know the
    // class of the element it works with.
    method accept(v: Visitor) is
        v.visitDot(this)

class Circle implements Shape is
    // ...
    method accept(v: Visitor) is
        v.visitCircle(this)

class Rectangle implements Shape is
    // ...
    method accept(v: Visitor) is
        v.visitRectangle(this)

class CompoundShape implements Shape is
    // ...
    method accept(v: Visitor) is
        v.visitCompoundShape(this)


// The Visitor interface declares a set of visiting methods that
// correspond to element classes. The signature of a visiting
// method lets the visitor identify the exact class of the
// element that it's dealing with.
interface Visitor is
    method visitDot(d: Dot)
    method visitCircle(c: Circle)
    method visitRectangle(r: Rectangle)
    method visitCompoundShape(cs: CompoundShape)

// Concrete visitors implement several versions of the same
// algorithm, which can work with all concrete element classes.
//
// You can experience the biggest benefit of the Visitor pattern
// when using it with a complex object structure such as a
// Composite tree. In this case, it might be helpful to store
// some intermediate state of the algorithm while executing the
// visitor's methods over various objects of the structure.
class XMLExportVisitor implements Visitor is
    method visitDot(d: Dot) is
        // Export the dot's ID and center coordinates.

    method visitCircle(c: Circle) is
        // Export the circle's ID, center coordinates and
        // radius.

    method visitRectangle(r: Rectangle) is
        // Export the rectangle's ID, left-top coordinates,
        // width and height.

    method visitCompoundShape(cs: CompoundShape) is
        // Export the shape's ID as well as the list of its
        // children's IDs.


// The client code can run visitor operations over any set of
// elements without figuring out their concrete classes. The
// accept operation directs a call to the appropriate operation
// in the visitor object.
class Application is
    field allShapes: array of Shapes

    method export() is
        exportVisitor = new XMLExportVisitor()

        foreach (shape in allShapes) do
            shape.accept(exportVisitor)

如果您想知道为什么我们需要accept此示例中的方法,我的文章Visitor and Double Dispatch详细解决了这个问题。

06 适用场景

当您需要对复杂对象结构(例如对象树)的所有元素执行操作时,请使用访问者。

访问者模式允许您通过让访问者对象实现相同操作的多个变体(对应于所有目标类)来对具有不同类的一组对象执行操作。

使用Visitor清理辅助行为的业务逻辑。

该模式通过将所有其他行为提取到一组访问者类中,使您的应用程序的主要类更加专注于它们的主要工作。

当行为仅在类层次结构的某些类中有意义,而在其他类中没有意义时,请使用该模式。

您可以将此行为提取到单独的访问者类中,并仅实现那些接受相关类对象的访问方法,其余为空。

07 如何实施

  1. 使用一组“访问”方法声明访问者接口,每个存在于程序中的具体元素类一个。

  2. 声明元素接口。如果您正在使用现有的元素类层次结构,请将抽象的“接受”方法添加到层次结构的基类中。此方法应接受访问者对象作为参数。

  3. 在所有具体元素类中实现接受方法。这些方法必须简单地将调用重定向到与当前元素的类匹配的传入访问者对象上的访问方法。

  4. 元素类只能通过访问者界面与访问者一起使用。然而,访问者必须知道所有具体元素类,作为访问方法的参数类型引用。

  5. 对于无法在元素层次结构中实现的每个行为,创建一个新的具体访问者类并实现所有访问方法。

    您可能会遇到访问者需要访问元素类的某些私有成员的情况。在这种情况下,您可以公开这些字段或方法,违反元素的封装,或者将访问者类嵌套在元素类中。只有当您幸运地使用支持嵌套类的编程语言时,后者才有可能。

  6. 客户端必须创建访问者对象并通过“接受”方法将它们传递给元素。

08 优缺点

图片

关注公众号可获取干货资料:《设计模式详解》


image.png

image.png
image.png

https://mp.weixin.qq.com/s?__biz=Mzk0NjI5NzE1Ng==&tempkey=MTE0OF9BUzFOTGxneC9hZm5oNVBxSUZTdmhwV2J6Uk04ZjMyaHRJNHFnbUI3OXNVcWZwdEtLMklzby14TnVvSVVDcXZ4LTFlUWVYQURuSWxDdW42NmNFV055ZFJHNkRrWnpXVkQzMHc3ZjVpcGl5b09INHhmTjhLUk9pTGdaRWNsa3BPbnZhVEFjZE5qNEpzb1FTWWZYdHZlcnpBSmRERVB4Q00xTGZUUl9nfn4%3D&chksm=4309019b747e888d49b5da010e577517edf0645bf6783680f638be5d68356b2fa7a05c8426ce#rd

你可能感兴趣的:(一文读懂访问者模式)