Import java.util.ArrayList;
Import java.util.List;
Abstract class Ivisitor
{
public abstract void Visit (Banana Banana);
public abstract void visit (rice);
public void Visit (ielement ielement)
{
System.out.println ("What, how to eat?") ");
}
}
Class Human extends Ivisitor
{
public void Visit (Banana Banana)
{
System.out.println ("Human clawed Skin eats bananas");
}
public void visit (rice)
{
System.out.println ("Human with tools to eat rice");
}
}
Class Monkey extends Ivisitor
{
public void Visit (Banana Banana)
{
System.out.println ("Monkeys do not Mr Skinner to eat");
}
public void visit (rice)
{
System.out.println ("Monkeys catch rice with their hands");
}
}
Interface IElement
{
public void Accept (Ivisitor ivisitor);
}
Class Banana implements IElement
{
public void Accept (Ivisitor ivisitor)
{
Ivisitor.visit (this);
}
}
Class Rice implements IElement
{
public void Accept (Ivisitor ivisitor)
{
Ivisitor.visit (this);
}
}
Class Apple implements IElement
{
public void Accept (Ivisitor ivisitor)
{
Ivisitor.visit (this);
}
}
Class Objectelementstruct
{
List<ielement> alist=new arraylist<ielement> ();
public void Add (IElement ielement)
{
Alist.add (ielement);
}
public void Accept (Ivisitor ivisitor)
{
for (ielement ielement:alist)
Ielement.accept (Ivisitor);
}
}
public class Visitorpatterntest
{
public static void Main (string[] args)
{
Objectelementstruct ob=new objectelementstruct ();
Ob.add (New Banana ());
Ob.add (New Rice ());
Ob.add (New Apple ());
Ob.accept (New Human ());
Ob.accept (New Monkey ());
}
}
16 of 23 Design Patterns in Java-visitor mode (visitor pattern)