Skip to content

Instantly share code, notes, and snippets.

@matklad
Created December 29, 2013 17:24
Show Gist options
  • Save matklad/8172568 to your computer and use it in GitHub Desktop.
Save matklad/8172568 to your computer and use it in GitHub Desktop.
Pattern matching of a poor man
import java.io.Serializable;
public class TwoAvgProtocol implements Serializable {
interface MessageReceiver {
public void onHave(double val);
public void onAdjust(double delta);
}
static abstract class Message {
protected abstract int getTag();
public void receive(MessageReceiver receiver) {
switch (getTag()) {
case 1:
receiver.onHave(((Have)this).val);
break;
case 2:
receiver.onAdjust(((Adjust)this).delta);
break;
default:
assert false;
}
}
}
static class Have extends Message {
public double val;
public Have(double val) {
this.val = val;
}
@Override
protected int getTag() {
return 1;
}
}
static class Adjust extends Message {
public double delta;
public Adjust(double delta) {
this.delta = delta;
}
@Override
protected int getTag() {
return 2;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment