Java visitor pattern 2 -


here followup question 1 asked better code example:

the following code use visitor pattern:

class animal { void accept(visitor v) { v.visit(this); } } class cat extends animal {} class dog extends animal {} class poodle extends dog {}  interface visitor {     public void visit(animal a);     public void visit(cat a);     public void visit(dog a);     public void visit(poodle a); }  class talkvisitor implements visitor {     public void visit(animal a) { system.out.println("?"); }     public void visit(cat a) { system.out.println("meow"); }     public void visit(dog a) { system.out.println("bark"); }     public void visit(poodle a) { system.out.println("arf"); } }      class walkvisitor implements visitor {     public void visit(animal a) { system.out.println("?"); }     public void visit(cat a) { system.out.println("sneak"); }     public void visit(dog a) { system.out.println("walk"); }     public void visit(poodle a) { system.out.println("skip"); } }   public class demo{     public static void main(string []args){         animal list[] = { new cat(), new dog(), new poodle() };          (animal : list)             a.accept(new talkvisitor());          (animal : list)             a.accept(new walkvisitor());         } }  

the output is:

? ? ? ? 

how can fix without adding switch of instanceof inside animal.accept()? (i don't want maintain switch() each time add new animal class)

i think doesn't make sense implement visit method abstract class (animal in case).

in visitor know possible subtypes. kind of basic assumption (otherwise add new methods visitor interface). gain ability dynamically implement different behaviors. in case talking , walking.

the price pay implement "accept" method in every concrete type. you've tried provide more general solution , got confused :) example take @ wikipedia description.

they talking different parts of car, idea same: implement accept method parts.

hope helps


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -