问题
I'm confronted with the following software design question: Is there still a need for the Visistor pattern in a programming language that supports open classes or class extensions?
I'm unsure. It can still be implemented, obviously, but it could also be replaced.
回答1:
Your question is not entirely valid. Should OOP-principle X be replaced by language feature Y? actually can never be answered because OOP principles are logically preceding language design questions, which are to a certain extent subject to available technologies, 'zeitgeist' and such things.
回答2:
Yes.
When you have a heterogeneous collection of types in your data model and various kinds of processing you'll need to do to it, the visitor pattern let's you implement each kind of processing separately, without cluttering up the interface of the basic data model classes.
For instance, maybe you need to make a pdf overview, export to a database, save to a file, perform some kind of graph analysis -- in each case examining all of the parts of the data model. Instead of adding a method to the interface of each element to do each kind of processing you need, the document model simply handles traversal, which gets implemented in only one place. The visitor is specialized to its process (a database exporter, e.g.) and has methods for processing each type of element. When a new element-type is added, the compiler forces you not to forget to add it to every visitor/processor. When a new process is added, it requires no change to the document model classes.
Here's a very good explanation of the visitor pattern.
And I found the wikipedia article on the visitor pattern helpful as well
来源:https://stackoverflow.com/questions/20824091/use-need-of-visitor-pattern-in-prog-lang-that-support-class-extensions-or-open