java - 访问者模式如何不违反开放/封闭原则?

标签 java design-patterns visitor-pattern open-closed-principle

From Wikipedia :

The idea was that once completed, the implementation of a class could only be modified to correct errors; new or changed features would require that a different class be created. That class could reuse coding from the original class through inheritance

据我了解,访问者模式是一种强大的技术,可以通过使用双重调度来遍历实现相同接口(interface)的相似但不同的对象。在我的一个 Java 示例中,我创建了一组构成树结构的复合对象,并且这些对象的每个特定实现都实现了可访问接口(interface)。访问者接口(interface)对每个可访问对象都有一个方法,具体的访问者实现了对每种情况执行的操作。

我想弄清楚的事实是,如果我要向也实现可访问的复合结构添加一个新实现,那么我需要重新打开访问者界面并将该案例添加到其中,还迫使我修改访问者的每个实现。

虽然这很好,因为无论如何我都需要这样做(如果访问者无法理解它们,添加到您的可访问对象有什么好处?)但是在学术层面上,这不会违反开放封闭原则?这难道不是设计模式的核心原因之一吗?试图展示切换到这种模式的正当理由,而不是维护一个 switch 语句来结束所有 switch 语句,但每个人都认为代码无论如何都是相同的,每个案例都有一个方法而不是 switch block ,只是分解了更难阅读。

最佳答案

模式适用于某些情况。来自 the GoF book (第 333 页):

Use the Visitor pattern when

  • [...]

  • the classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.

如果您经常更改构成结构的对象的类,则访问者类层次结构可能难以维护。在这种情况下,在构成结构的类上定义操作可能会更容易。

关于java - 访问者模式如何不违反开放/封闭原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979160/

相关文章:

design-patterns - 访问者选择如何遍历的访问者模式

java - 迭代另一个类中的链接列表(Java Applet)

c++ - c++中基于大型决策树的人工智能设计模式

java - 访问者模式接受不识别对象的类

C++ 避免向下转型或变体

java - 福勒的模式 : Dealing with table inheritance in a specific way

java - 如何使用 "VersionOne SDK JAVA API"客户端创建缺陷

java - 生成 WSDL 文件

java - 如何使用 Spring Security 将 'Remember me' 复选框引入现有项目?

java - 使用实现一对接口(interface)的成对类