Visitor: Defines a new operation to a class without change. Represent
an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of
the elements on which it operates.
Different with observer, Don’t think observe even a bit when you try
to understand visitor. They are totally different.
You have a solid class structure. I don’t add or delete class from
this structure. (Structure of company usually is stable)
You have a container to contain these objs( All empoyees in one
company ). and you need to loop these objs to apply an operation.
For different kind objs, operation should be a little different.
(calculateSalary() operation ,Manager*1.5, and Developer*1.2). A
nature way is to define calculateSalary virutal function in base
class.
Problem one is We need add another operation, such as audit(),
performance(), bodycheck()..... Whenever you add an operation,
you need to change all class interface.
Problem two is WE mush put all kinds of operation into one
class. Furthermore, some common parts have to distribute among
different class.
class structure solid, but operation flexible. You can
abstract each operation as a concreteVisitor. Add operation iseasy, but changing class in class struture is very difficult.
If container include different type of class, for example, company
container include all Employee objs and also include Car objs,
This time, visitor pattern is you only option.