Following on the series of posts on design patterns I will be talking
about the Visitor Pattern today. Visitor is behavioral pattern. You can
read about the other behavioral patterns from the following links.
Suppose you need to add a new method to a structure of classes, you
might end up damaging the design. This is where the visitor pattern
comes into play. The visitor pattern deals with performing new
operations on all elements of an existing hierarchy of classes without
altering the the classes themselves.
The visitor pattern is mainly made up of 2 components, the classes that
make up the hierarchy and the methods that are applied to these classes.
These methods are called as visitors. In the following example there is
one visitor viz. SalaryVisitor which increments a persons salary.
The following example is based on the example shown in the Dofactory
site
The visitor pattern provides number of ways to modify the behavior of a
hierarchy of classes without modifying the classes. We can use the
visitor pattern when we have a hierarchy that is sealed or when there
are many operations to perform on it or when we need the flexibility of
defining new operations.
In my next post I will be writing about the Interpreter pattern.
Comments