4 ms·
The visitor pattern is a way around a lack of multiple dispatch: choosing a method based on the run-time type of all arguments. Common Lisp, for example, has n
by martincmartin 14y ago
The visitor pattern is a way around a lack of multiple dispatch: choosing a method based on the run-time type of all arguments. Common Lisp, for example, has no need of the visitor pattern since it has multiple dispatch.
The O.P. is about when the design patterns are needed, not what you need to implement them.
Incidentally, the visitor pattern doesn't require OO for implementation, it requires a type system and single dispatch, i.e. choosing a method based on the run-time type of its first argument. Python doesn't have single dispatch. So the visitor pattern doesn't really work in Python, you essentially have to code a huge number of branches, e.g. n switch statements, each with n cases, in order to dispatch n^2 ways.
- omaranto 14y agoWait, what? Python doesn't have single dispatch? How does it pick which block of code to run when you say a.f(x)? That dispatches on the class of a doesn't it?
- skittles 14y agoYou're correct. Python objects have methods that explicitly take "self" as the first argument. In Java and C#, self or "this" is implied. They all are single-dispatch languages unless an add-on library is used.
- martincmartin 14y agoYeah you're right. My bad, I was thinking of f(x, y). a.f(x) is single dispatch - just like C++ and Java.