zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Understanding the need of Visitor Pattern

The of pattern need Understanding
2023-09-11 14:14:17 时间

Understanding the need of Visitor Pattern

The visitor pattern is a solution to a more general design problem:

I have a hierarchy of different classes. Each class supports various common operations. We would now like to extend that hierarchy, without having to change the existing hierarchy (e.g. because it is defined by a library we do not have the source code to).

  • We can add more classes, which must support all required operations.
  • We can add more operations, which must be supported by all classes in the hierarchy.

When designing a hierarchy, we can choose which of the two extension directions we want to make easy. (Trying to do both is called the Expression Problem and is extremely tricky.)

Since this is a bit theoretic, let's use an example – various kinds of animals. Each animal has a name() and makes a sound().