Skip to content

Instantly share code, notes, and snippets.

@matklad
Last active December 5, 2016 20:57
Show Gist options
  • Save matklad/76efd5ae9755e5650708162884c89ed0 to your computer and use it in GitHub Desktop.
Save matklad/76efd5ae9755e5650708162884c89ed0 to your computer and use it in GitHub Desktop.
abstract class Query {
class Sum {
}
class Add {
}
void process(Consumer<Sum> onSum, Consumer<Add> onAdd) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for (int i = 0; i < n; i++) {
String word = s.next();
switch (word) {
case "A":k
onAdd.accept(new Add());
break;
case "S":
onSum.accept(new Sum());
break;
default:
throw new IllegalStateException("Bad input: " + word);
}
}
}
}
package com.company;
abstract class Query {
interface Visitor<T> {
T visitSum(Sum sum);
T visitAdd(Add add);
}
abstract <T> T accept(Visitor<T> visitor);
final class Add extends Query {
final int amount;
final int left;
final int right;
Add(int amount, int left, int right) {
this.amount = amount;
this.left = left;
this.right = right;
}
@Override
<T> T accept(Visitor<T> visitor) {
return visitor.visitAdd(this);
}
}
final class Sum extends Query {
final int left;
final int right;
Sum(int left, int right) {
this.left = left;
this.right = right;
}
@Override
<T> T accept(Visitor<T> visitor) {
return visitor.visitSum(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment