Accessor

motivation

  • In the process of software construction, due to changes in requirements, new behaviors (methods) are often added to certain class hierarchies. If such changes are made directly in the base class, it will bring a heavy burden of changes to the subclasses. , And even destroy the original design.
  • How to dynamically add new operations for each class on the class hierarchy transparently as needed at runtime without changing the class hierarchy, so as to avoid the above problems?

Mode definition

  • Represents an operation that acts on each element in an object structure. It makes it possible to define (expand) new operations (changes) acting on these elements without changing (stabilizing) the classes of each element.

Summary of main points

  • The Visitor mode uses the so-called double dispatch to achieve dynamic addition of new ones for each class on the class hierarchy transparently at runtime without changing (no adding new operations-compile time) the Element class hierarchy Operation (support changes).
  • The so-called double distribution means that the Visitor mode contains two polymorphic distributions (note the polymorphic mechanism): the first is the polymorphic analysis of the accept method; the second is the polymorphic analysis of the visitElementX method.
  • The biggest disadvantage of the Visitor pattern is to extend the class hierarchy (add new Element subclasses), which will lead to changes in the Visitor class. Therefore, the Visitor mode is suitable for "Element class hierarchical structure is stable, but its operations often face frequent changes."

Guess you like

Origin blog.csdn.net/oTianLe1234/article/details/113960329