简体   繁体   中英

Java sealed type with pattern switches VS pattern Visitor

An aside: Before java 15 to remedy this people used the "type safe visitor" pattern. I recommend not learning that for your sanity, but if you are curious you can look at code ANTLR generates - its all a large hierarchy of differently "shaped" data structures.

Source: section 2, What is the point of a “sealed interface” in Java?

In the case where we use Visitor to avoid multiple instanceof:

  • What is the advantage to use pattern Visitor rather than using sealed type with switch pattern matching?
  • What is the advantage to use sealed with switch pattern matching type rather than using Visitor?
  • Should we stop using Visitor?

What is the advantage to use pattern Visitor rather than using sealed type with switch pattern matching?

Visitor decouples the sender class from the dispatched classes. Adding a class to the hierarchy of objects doesn't modify the sender class, so it complies with OCP principle. It also complies with LSP principle, because it guarantees the implementation of the visited method and safe execution.

What is the advantage to use sealed with switch pattern matching type rather than using Visitor?

Simplicity. Not so many additional classes, addition of dispatched classes is easier. It is also easier to debug. The understanding of double dispatch mechanism is not needed as well.

Should we stop using Visitor?

No.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM