– http://butunclebob.com/ArticleS.UncleBob.IuseVisitor (Single Reponsibility Principle)
– extending base class and child classes without changing them, by encapsulating same method calls for different child classes into a single new class
e.g. Animal, Cat, Dog grouping new sleep(Cat c), sleep(Dog d) into an individual class.
– GoF, “Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure.”
– easier to add same method to each class which is difficult for OO languages not supporting double dispatch
– visitor pattern uses the class type in the visit() method to determine the various visitables.
– The visitor has several overloaded visit() methods with different concrete visitable class types as parameters while visitables have a generic accept() method of a visitor.
– so visitables accept() a generic visitor, then call visitor.visit(this) which is a specific concrete call matching its own class type defined in the visitor interface.
– workaround in language not support double dispatch
– to extend interface without changing original interface
– keep main logic clean and move messy logic elsewhere
– enhance visitor pattern with reflection
– replace a chain of instanceof with visitor pattern