Tags

links:
http://www.artima.com/cppsource/top_cpp_aha_moments.html
http://stackoverflow.com/questions/255214/when-should-i-use-the-visitor-design-pattern
https://dzone.com/articles/design-patterns-visitor
http://www.javaworld.com/article/2077602/learn-java/java-tip-98–reflect-on-the-visitor-design-pattern.html
http://stackoverflow.com/questions/2790144/avoiding-instanceof-in-java
http://alexshabanov.com/2011/12/03/instanceof-vs-visitor/
http://www.avajava.com/tutorials/lessons/visitor-pattern.html?page=1
http://butunclebob.com/ArticleS.UncleBob.IuseVisitor (Single Reponsibility Principle)

summary:
– 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

Advertisements