Skip to content

Instantly share code, notes, and snippets.

@Riduidel
Created December 10, 2020 06:31
Show Gist options
  • Save Riduidel/c89a12f39e0d55fa2b21b88a685f7a8f to your computer and use it in GitHub Desktop.
Save Riduidel/c89a12f39e0d55fa2b21b88a685f7a8f to your computer and use it in GitHub Desktop.
Visitor -5 - main avec visiteur retournant un type générique
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Feuille implements Visitable {
public String montrerFeuille() { return "🍃"; }
@Override public <Type> Type accept(Visitor<Type> v) { return v.visit(this); }
}
class Fleur implements Visitable {
public String afficherFleur() { return "🌺"; }
@Override public <Type> Type accept(Visitor<Type> v) { return 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 <Type> Type accept(Visitor<Type> v) {
v.startVisit(this);
for(Visitable c : children) {
c.accept(v);
}
return v.endVisit(this);
}
}
interface Visitable {
public <Type> Type accept(Visitor<Type> v);
}
interface Visitor<Type> {
Type visit(Feuille feuille);
Type visit(Fleur fleur);
void startVisit(Branche branche);
Type 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) {
System.out.println(v.accept(new Visitor<String>() {
@Override public String visit(Feuille feuille) {
return feuille.montrerFeuille();
}
@Override public String visit(Fleur fleur) {
return fleur.afficherFleur();
}
@Override public void startVisit(Branche branche) {
}
@Override public String endVisit(Branche branche) {
return "⬅🌿";
}
}));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment