Created
February 8, 2015 21:51
-
-
Save kevinpet/7375f3c8f4a4b49be3cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Foo { | |
abstract <T> T match(Visitor<T> visitor); | |
interface Visitor<T> { | |
T caseBar(Bar b); | |
T caseBaz(Baz b); | |
} | |
static class Bar extends Foo { | |
final int bar; | |
private Bar(int bar) { | |
this.bar = bar; | |
} | |
@Override | |
<T> T match(Visitor<T> visitor) { | |
return visitor.caseBar(this); | |
} | |
} | |
static class Baz extends Foo { | |
final String baz; | |
private Baz(String baz) { | |
this.baz = baz; | |
} | |
@Override | |
<T> T match(Visitor<T> visitor) { | |
return visitor.caseBaz(this); | |
} | |
} | |
static void handle(Foo f) { | |
System.out.println(f.match(new Visitor<String>() { | |
@Override | |
public String caseBar(Bar b) { | |
return "I have " + b.bar + " bars"; | |
} | |
@Override | |
public String caseBaz(Baz b) { | |
return "I have the " + b.baz + " baz"; | |
} | |
})); | |
} | |
public static void main(String[] args) { | |
handle(new Bar(42)); | |
handle(new Baz("Luhrmann")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment