Skip to content

Instantly share code, notes, and snippets.

@kandran
Last active August 29, 2015 14:18
Show Gist options
  • Save kandran/62ee8ba0dc47033d609d to your computer and use it in GitHub Desktop.
Save kandran/62ee8ba0dc47033d609d to your computer and use it in GitHub Desktop.
Design pattern visitor en java (http://kandran.fr/design-pattern-visiteur)
interface IVisitable {
void accept(IVisitor visitor);
}
class Book implements IVisitable
{
public String support = "unknown";
public void accept(IVisitor visitor)
{
visitor.visit(this);
}
}
class PaperBook extends Book
{
public String support = "paper";
}
class EBook extends Book
{
public String support = "numeric";
public Float price = 5;
}
interface IVisitor {
void visit(IVisitable o);
void visit(EBook o);
void visit(PaperBook o);
void visit(Book o);
}
class DebugVisitor implements IVisitor
{
public void visit(EBook o)
{
System.out.println("We have an ebook so it's support is " + o.support + " and it's price is" + o.price);
}
public void visit(PaperBook o)
{
System.out.println("We have a classic book so it's support is made of " + o.support);
}
public void visit(Book o)
{
System.out.println("We have a ebook - but we doesn't know this kind so it's support is " + o.support);
}
public void visit(IVisitable o)
{
System.out.println("Not implemented yet");
}
public class MainRun
{
public static void main(String[] args)
{
DebugVisitor visitor = new DebugVisitor();
EBook ebook = new EBook();
/* Display = We have an ebook so it's support is numeric and it's price is 5*/
ebook.accept(visitor);
PaperBook paperBook = new PaperBook();
/* Display = We have a classic book so it's support is made of paper */
paperBook.accept(visitor);
Book book = new Book();
/* Display = "We have a ebook - but we doesn't know this kind so it's support is unknown */
book.accept(visitor);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment