Skip to content

Instantly share code, notes, and snippets.

@Riduidel
Created December 10, 2020 06:29
Show Gist options
  • Save Riduidel/161b38bbf13cb33c10ba4435b81daeb4 to your computer and use it in GitHub Desktop.
Save Riduidel/161b38bbf13cb33c10ba4435b81daeb4 to your computer and use it in GitHub Desktop.
Visitor - 4 - main avec visiteur arborescent
class Feuille implements Visitable {
public String montrerFeuille() { return "🍃"; }
@Override public void accept(Visitor v) { v.visit(this); }
}
class Fleur implements Visitable {
public String afficherFleur() { return "🌺"; }
@Override public void accept(Visitor v) { v.visit(this); }
}
class Branche implements Visitable {
List<Visitable> children = new ArrayList<Visitable>();
public Branche(List<Visitable> children) { this.children.addAll(children); }
public Branche(Visitable...children) { this(Arrays.asList(children)); }
@Override public void accept(Visitor v) {
v.startVisit(this);
for(Visitable c : children) {
c.accept(v);
}
v.endVisit(this);
}
}
interface Visitable {
public void accept(Visitor v);
}
interface Visitor {
void visit(Feuille feuille);
void visit(Fleur fleur);
void startVisit(Branche branche);
void endVisit(Branche branche);
}
public class Main {
public static void main(String[] args) {
List<Visitable> visitables = Arrays.asList(new Feuille(), new Fleur(),
new Branche(new Feuille(), new Fleur()));
for (Visitable v : visitables) {
v.accept(new Visitor() {
@Override public void visit(Feuille feuille) {
System.out.println(feuille.montrerFeuille());
}
@Override public void visit(Fleur fleur) {
System.out.println(fleur.afficherFleur());
}
@Override
public void startVisit(Branche branche) {
System.out.println("➡🌿");
}
@Override
public void endVisit(Branche branche) {
System.out.println("⬅🌿");
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment