16 of 23 Design Patterns in Java-visitor mode (visitor pattern)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.