I was studying the visitor pattern and came across this useful example: https://stackoverflow.com/a/2604798/974594. The post is very clear and very easy to understand, altought, i’m having problems understanding the last part, starting here:
With that said, visitors are usually overkill, and they have a
tendency grossly complicate APIs, and it can be very cumbersome to
define a new visitor for every new kind of behavior.Usually, simpler patterns like inheritance should be used in place of
visitors. For example, in principle I could write a class like:class FruitPricer : IFruitVisitor { public double Price { get; private set; } public void Visit(Orange fruit) { Price = 0.69; } public void Visit(Apple fruit) { Price = 0.89; } public void Visit(Banana fruit) { Price = 1.11; } }It works, but what’s the advantage over this trivial modification:
abstract class Fruit
{ public abstract void Accept(IFruitVisitor visitor); public abstract double Price { get; } }
I’m not getting what is he saying here. I mean, if he now want to implement the feature ‘price’, what must be changed/added to the existing code (based on this pattern approach)?=
The answer you reference misses much of the point of Visitor. It says “visitors are used to implement type-testing without sacrificing type-safety”, which is simply incorrect. The GOF book says “visitors let you define a new operation without changing the classes of the elements on which it operates”. Visitors can certainly be used for testing objects on things other than type, and for carrying out operations on objects that don’t involve testing.
“Visitor is overkill” is frequently stated, but it’s usually said by people trying to use Visitor for things it wasn’t intended for, and then finding that -surprise – it doesn’t really work for it.
The poster is right in that the second piece of code they quote is a much easier way of implementing the functionality, but it misses the point in that Visitor is intended for when you don’t want to modify the Fruit class.